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

Posted by Chris on Stack Overflow See other posts from Stack Overflow or by Chris
Published on 2010-04-19T14:22:19Z Indexed on 2010/04/19 14:23 UTC
Read the original article Hit count: 180

Filed under:
|
|

Hello, 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?

© Stack Overflow or respective owner

Related posts about java

Related posts about generics