我怎样才能做到这一点?
public class GenericClass<T>
{
public Type getMyType()
{
//How do I return the type of T?
}
}
Run Code Online (Sandbox Code Playgroud)
到目前为止我尝试的所有东西总是返回类型Object而不是使用的特定类型.
这是我的代码:ExecutorImp扩展了AbstractExecutor,它提取了与其实现者相同的执行逻辑(ExecutorImp就是一例),当调用ExecutorImp的execute()方法时,它将调用其超类型中的方法,但是超类型(AbstractExcutor) )应该知道另一个绑定到实现者的类(在示例中,它是User类):
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
abstract class AbstractExecutor<E> {
public void execute() throws Exception {
ArrayList<E> list = new ArrayList<E>();
// here I want to get the real type of 'E'
Class cl = this.getClass().getTypeParameters()[0].getGenericDeclaration().getClass();
Object o = cl.getConstructor(String.class).newInstance("Gate");
list.add((E) o);
System.out.println(format(list));
}
public abstract String format(ArrayList<E> list);
public abstract String getType();
}
public class ExectorImp<E> extends AbstractExecutor<User> {
@Override
public String getType() {
return "user";
}
@Override
public String format(ArrayList<User> list) {
StringBuffer sb = new StringBuffer();
for …Run Code Online (Sandbox Code Playgroud)