Java:获取泛型类型
我正在为 C++ 编写 Java 包装器,并希望使用泛型类来包装 C++ 模板。因此,我想获取 String 形式的泛型类型,以便我可以进一步将其传递给 JNI 并实例化相应的 C++ 对象。
编辑:这就是我的实现方式,以防有人感兴趣:
public class A<T>
{
private long ptr;
public static <E> A<E> create(Class<E> cls)
{
return new A<E>(cls);
}
private A(Class<T> cls)
{
ptr = create( cls.getName() );
if(ptr == 0)
{
throw new NullPointerException();
}
}
private native long create(String className);
}
I'm writing a Java wrapper for c++ and would like to use a generic class to wrap a c++ template. Therefore I'd like to get the generic type as String so I can further pass it to JNI and instantiate a corresponding c++ object.
EDIT: this is how I implemented it, in case someone is interested:
public class A<T>
{
private long ptr;
public static <E> A<E> create(Class<E> cls)
{
return new A<E>(cls);
}
private A(Class<T> cls)
{
ptr = create( cls.getName() );
if(ptr == 0)
{
throw new NullPointerException();
}
}
private native long create(String className);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于 类型擦除<,Java 泛型不会在编译时保留类型信息/a>.您需要将 T 类的实例传递给 A 类:
Java generics don't preserve type information past compile time, due to type erasure. You need to pass an instance of T's class to your A class: