1

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); 
}
1
  • well, how can I do that? I can't simply write T.getClass().toString() Commented Nov 6, 2011 at 20:25

1 Answer 1

4

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); 
}
Sign up to request clarification or add additional context in comments.

3 Comments

Eventually the code isn't used only by myself, so I am looking for a more elegant solution. Instantianting objects like this: A<String> a = new A<String>(String.class); isn't very user-friendly.
@Pedro a) Java Generics were designed that way, there's nothing we can do. b) you could improve the code by using a static factory method: A<String> a = A.ofType(String.class)
@Sean - the factory method is a nice suggestion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.