Pedro
Pedro

Reputation: 4160

Java: get generic type

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); 
}

Upvotes: 1

Views: 3677

Answers (1)

Ted Hopp
Ted Hopp

Reputation: 234795

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); 
}

Upvotes: 4

Related Questions