开发者

Is there a nice way of having static generic parameters is Java?

开发者 https://www.devze.com 2022-12-27 15:17 出处:网络
recently I\'m writing some functions that I take from Haskell and translate into Java. One of the main problems I have is I cannot easily create a static property with a generic type. Let me explain b

recently I'm writing some functions that I take from Haskell and translate into Java. One of the main problems I have is I cannot easily create a static property with a generic type. Let me explain by a little example...

// An interface to implement functions
public interface Func<P, R> {
    public R apply(P p);
}

// What I want to do..开发者_开发百科. (incorrect in Java)
public class ... {
    public static <T> Func<T, T> identity = new Func<T, T>() {
        public T apply(T p) { return p; }
    }
}

// What I do right now
public class ... {
    private static Func<Object, Object> identity = new Func<Object, Object>() {
        public Object apply(Object p) { return p; }
    }
    @SuppressWarnings("unchecked")
    public static <T> Func<T, T> getIdentity() {
        return (Func<T, T>)identity;
    }
}

Are there any easier ways to do something like that? What kind of problems might arise if the syntax I used would be valid?


Just create a new tiny little object each time, for some definition of "each time". Remember that allocations on typical JREs are tiny, but GCing static data is expensive.

Whilst I think your syntax could be made to work without compatibility issues, it would be add complexity and irregularity whilst not bringing a huge amount on benefit.


I think the way you're currently doing it is about the easiest you're going to find.

The issue is due to the way the Java Platform implements Generics internally -- since it uses type erasure (for backward compatibility reasons), type information is lost at compile time and prevents the usage of Generics in situations like static declarations, since those kinds of declarations typically require the type information to be compiled in (which Java currently won't do for Generics).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号