如何获得T型泛型的类实例我有个仿制类,Foo<T>..用一种方法Foo,我想获得类型T的类实例,但我不能调用T.class.使用T.class?
3 回答
拉莫斯之舞
TA贡献1820条经验 获得超10个赞
Class
class Foo<T> {
final Class<T> typeParameterClass;
public Foo(Class<T> typeParameterClass) {
this.typeParameterClass = typeParameterClass;
}
public void bar() {
// you can access the typeParameterClass here and do whatever you like
}}
RISEBY
TA贡献1856条经验 获得超5个赞
Foo
Foo<MyType> myFoo = new Foo<MyType>(){};T
Type mySuperclass = myFoo.getClass().getGenericSuperclass();Type tType = ((ParameterizedType)mySuperclass).getActualTypeArguments()[0];
mySuperclassT.
new Foo<MyType>(){}new Foo<MyType>(MyType.class);
import java.lang.reflect.ParameterizedType;import java.lang.reflect.Type;import java.util.ArrayDeque;import java.util.Deque;
import java.util.NoSuchElementException;/**
* Captures and silently ignores stack exceptions upon popping.
*/public abstract class SilentStack<E> extends ArrayDeque<E> {
public E pop() {
try {
return super.pop();
}
catch( NoSuchElementException nsee ) {
return create();
}
}
public E create() {
try {
Type sooper = getClass().getGenericSuperclass();
Type t = ((ParameterizedType)sooper).getActualTypeArguments()[ 0 ];
return (E)(Class.forName( t.toString() ).newInstance());
}
catch( Exception e ) {
return null;
}
}}public class Main {
// Note the braces...
private Deque<String> stack = new SilentStack<String>(){};
public static void main( String args[] ) {
// Returns a new instance of String.
String s = stack.pop();
System.out.printf( "s = '%s'\n", s );
}}添加回答
举报
0/150
提交
取消
