I\'m making a MethodPointer
class in order to simulate the functionality of function pointers from C++. At first, I was doing everything with just Object
SLaks' answer points out that object.getClass()
decays to Class extends Object>
, to explain the compile error. But it's not safe to cast to Class
.
getClass "returns the runtime class" of the object it's called on. For example, if we're inside a MethodPointer
, then object
is-a Number
but its runtime type could be Integer
, Double
, etc. That tells us that casting object.getClass()
to Class
isn't safe because Class
and Class
are different objects, representing different classes - a distinction that seems very relevant to the correctness of what you're trying to do.
So what's the solution? Well, don't cast. Insist on taking a Class
from the caller.