Java: get generic type

前端 未结 1 1845
天涯浪人
天涯浪人 2020-12-21 20:00

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

相关标签:
1条回答
  • 2020-12-21 20:55

    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:

    public class A<T>
    {
        private Class<T> type;
        private long ptr; 
    
        public class A(Class<T> type)
        {
            this.type = type;
            ptr = create( getGenericType() ); 
    
            if(ptr == 0)
            {
                throw new NullPointerException(); 
            }
         }
    
        private String getGenericType()
        {
            return type.getName();
        }
    
        private native long create(String className); 
    }
    
    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题