开发者

Initializing variable. I don't know their type [java]

class pair<U,V>{
U first;
V second;
public pair() {
    first = new U(); //error
    second = 开发者_开发知识库new V(); //error
}   
public pair(U f,V s){
    first = f;
    second = s;
}
}

required: class

found: type parameter

Is it possible to initialize first/second with (without-arguments) constructor of U/V type other way?


Java does not normally allow this because of type erasure. You can specify constructor arguments of type Class<U> and Class<V>, for which you would pass in concrete class types of the given type parameters (i.e., Integer.class and String.class for <Integer> and <String>).

It is also possible to extract the type using bytecode-level reflection, but quite complicated, and it doesn't always work in all situations. If you scroll down on this article, you can find the example that makes this possible. I've pasted it below for convenience.

static public Type getType(final Class<?> klass, final int pos) {
    // obtain anonymous, if any, class for 'this' instance
    final Type superclass = klass.getGenericSuperclass();

    // test if an anonymous class was employed during the call
    if ( !(superclass instanceof Class) ) {
        throw new RuntimeException("This instance should belong to an anonymous class");
    }

    // obtain RTTI of all generic parameters
    final Type[] types = ((ParameterizedType) superclass).getActualTypeArguments();

    // test if enough generic parameters were passed
    if ( pos < types.length ) {
        throw RuntimeException(String.format("Could not find generic parameter #%d because only %d parameters were passed", pos, types.length));
    }

    // return the type descriptor of the requested generic parameter
    return types[pos];
}

Edit: for reply to comment:

class pair<U,V>{
    U first;
    V second;
    public pair(Class<U> cu, Class<V> cv) {
        try {
            first = cu.newInstance();
            second = cv.newInstance();
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
    }   
    public pair(U f,V s){
        first = f;
        second = s;
    }
}


Nope you can't, the types get erased in Java. So you should move construction to the call site.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜