这是我的代码: ExecutorImp继承了抽象执行器AbstractExecutor,该抽象执行器提取了其实现者(ExecutorImp是其中之一)相同的执行逻辑。当调用ExecutorImp的execute()方法时,它将调用其超类型中的方法,但是超类型(即AbstractExecutor)应该知道绑定到实现者的另一个类(在本例中为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 (User u : list) {
sb.append(u.toString() + " ");
}
return sb.toString();
}
public static void main(String[] args) throws Exception {
new ExectorImp().execute();
}
}
class User {
String name;
public User(String name) {
this.name = name;
}
}
那么,我的代码有什么问题?