Ответ 1
Java обычно не разрешает это из-за типа erasure. Вы можете указать аргументы конструктора типа Class<U>
и Class<V>
, для которых вы должны передать конкретные типы классов заданных параметров типа (т.е. Integer.class
и String.class
для <Integer>
и <String>
).
Также можно извлечь тип с использованием отражения на уровне байт-кода, но довольно сложно, и он не всегда работает во всех ситуациях. Если вы прокрутите страницу в этой статье, вы можете найти пример, который сделает это возможным. Я добавил его ниже для удобства.
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];
}
Изменить: для ответа на комментарий:
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;
}
}