java - Why is casting the class of a generic to Class<T> unsafe? -
i'm making methodpointer class in order simulate functionality of function pointers c++. @ first, doing objects, had thought -- why not make generic?
the problem came in constructor, attempted call constructor signature methodpointer(class<t> clazz, string methodname, class<?> ... paramclasses):
public methodpointer(t object, string methodname, class<?> ... paramclasses) { this(object.getclass(), methodname, paramclasses); this.object = object; } i assumed work fine, received following compiler error:
the constructor methodpointer<t>(class<capture#1-of ? extends object>, string, class<?>[]) undefined so, confused, did this:
public methodpointer(t object, string methodname, class<?> ... paramclasses) { this((class<t>) object.getclass(), methodname, paramclasses); this.object = object; } it compiles, receive following warning:
unchecked cast class<capture#1-of ? extends object> class<t> i guess problem don't understand class<capture#1-of ? extends object> means. thought since type of t inferred t object parameter necessary calling object.getclass() returns class object of type class<t>. apparently isn't case, though. can clear confusion?
full class declaration , constructors:
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 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; }
slaks' answer points out object.getclass() decays class<? extends object>, explain compile error. it's not safe cast class<t>.
getclass "returns runtime class" of object it's called on. example, if we're inside methodpointer<number>, object is-a number runtime type integer, double, etc. tells casting object.getclass() class<t> isn't safe because class<integer> , class<number> different objects, representing different classes - distinction seems relevant correctness of you're trying do.
so what's solution? well, don't cast. insist on taking class<t> caller.
Comments
Post a Comment