Why is casting the class of a generic to Class unsafe?

后端 未结 3 1162
再見小時候
再見小時候 2021-01-13 05:24

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

相关标签:
3条回答
  • 2021-01-13 05:56

    The problem is that getClass() ignores type parameters.

    The Javadocs say:

    The actual result type is Class<? extends |X|> where |X| is the erasure of the static type of the expression on which getClass is called.

    For example, new ArrayList<String>().getClass() returns a Class<? extends ArrayList>, not Class<? extends ArrayList<String>>.

    This also means that getClass() called on a type parameter decays to a Class<? extends Object>.

    0 讨论(0)
  • 2021-01-13 06:00

    If you do not need an specified Class-type, you could use

    Class<?>
    

    for you parameters.

    So you have an unbound Type for your classes.

    And if you want to get an instance you could use it like this:

    obj.getClass().getDeclaredConstructor(Class<?> parameterTypes)
    
    0 讨论(0)
  • 2021-01-13 06:07

    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<T>.

    getClass "returns the runtime class" of the object it's called on. For example, if we're inside a MethodPointer<Number>, then object is-a Number but its runtime type could be Integer, Double, etc. That tells us that casting object.getClass() to Class<T> isn't safe because Class<Integer> and Class<Number> 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<T> from the caller.

    0 讨论(0)
提交回复
热议问题