我正在创建一个MethodPointer
类以模拟 C++ 中函数指针的功能。起初,我只是用Object
s 来做所有事情,但后来我有了一个想法——为什么不让它真正通用呢?
问题出现在这个构造函数中,它试图用签名调用另一个构造函数MethodPointer(Class<T> clazz, String methodName, Class<?> ... paramClasses)
:
public MethodPointer(T object, String methodName, Class<?> ... paramClasses) {
this(object.getClass(), methodName, paramClasses);
this.object = object;
}
我认为这可以正常工作,但我收到以下编译器错误:
The constructor MethodPointer<T>(Class<capture#1-of ? extends Object>,
String, Class<?>[]) is undefined
所以,很困惑,我这样做了:
public MethodPointer(T object, String methodName, Class<?> ... paramClasses) {
this((Class<T>) object.getClass(), methodName, paramClasses);
this.object = object;
}
它现在可以编译,但我收到以下警告:
Unchecked cast from Class<capture#1-of ? extends Object> to Class<T>
我想问题是我不明白什么Class<capture#1-of ? extends Object>
意思。我认为,由于从参数T
推断出的类型,调用返回一个类型的对象是必要的。不过,显然情况并非如此。有人可以解决我的困惑吗?T object
object.getClass()
Class
Class<T>
完整的类声明和所有构造函数:
public class MethodPointer<T> {
//Logger instance
private static final Logger LOGGER = Logger.getLogger(MethodPointer.class);
//Object fields
private final Method method;
private ArrayList<Object> args = new ArrayList<Object>();
private T object = null;
//Constructors
public MethodPointer(Method method) {
this.method = method;
}
public MethodPointer(Class<T> clazz, String methodName, Class<?> ... paramClasses) {
Method theMethod = null;
try {
theMethod = clazz.getMethod(methodName, paramClasses);
}
catch(NoSuchMethodException nsme) {
LogUtil.log(LOGGER, Level.ERROR, "Unable to find method " + methodName + " in " + clazz.getSimpleName(), nsme);
}
method = theMethod;
}
public MethodPointer(T object, String methodName, Class<?> ... paramClasses) {
this((Class<T>) object.getClass(), methodName, paramClasses);
this.object = object;
}