Java 有静态泛型参数的好方法吗?
最近我正在编写一些从 Haskell 获取的函数并将其转换为 Java。 我遇到的主要问题之一是我无法轻松创建具有泛型类型的静态属性。让我用一个小例子来解释......
// 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;
}
}
有没有更简单的方法来做这样的事情? 如果我使用的语法有效,可能会出现什么样的问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
每次只需创建一个新的小对象,以实现“每次”的某种定义。请记住,典型 JRE 上的分配很小,但 GC 静态数据的成本很高。
虽然我认为你的语法可以在没有兼容性问题的情况下工作,但这会增加复杂性和不规则性,同时不会带来巨大的好处。
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.
我认为你目前正在做的方式是你能找到的最简单的方式。
这个问题是由于 Java 平台内部实现泛型的方式造成的——因为它使用类型擦除(出于向后兼容性的原因),类型信息在编译时丢失,并阻止在静态声明等情况下使用泛型,因为这些类型声明通常需要编译类型信息(Java 目前不会为泛型执行此操作)。
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).