我有办法

public static <T, U extends T> void method(T source, T destination, Class<U> class){}


适用于

O.method(string1, string2, string1.getClass());


但是如果我将方法更改为

public static <T> void method(T source, T destination, Class<T> myclass){}


它不会编译。为什么?

最佳答案

object.getClass()返回Class<?>类型,其中?是任何类型。因此,对于任何类,您都无法确定返回的类的类型。

下面更多了解的是getClass方法的文档注释

 /**
     * Returns the runtime class of this {@code Object}. The returned
     * {@code Class} object is the object that is locked by {@code
     * static synchronized} methods of the represented class.
     *
     * <p><b>The actual result type is {@code Class<? extends |X|>}
     * where {@code |X|} is the erasure of the static type of the
     * expression on which {@code getClass} is called.</b> For
     * example, no cast is required in this code fragment:</p>
     *
     * <p>
     * {@code Number n = 0;                             }
     * {@code Class<? extends Number> c = n.getClass(); }
     * </p>
     *
     * @return The {@code Class} object that represents the runtime
     *         class of this object.
     * @jls 15.8.2 Class Literals
     */


更重要的是,请注意文档注释中的The actual result type is {@code Class<? extends |X|>} where {@code |X|} is the erasure of the static type of the expression on which {@code getClass} is called.行。

关于java - .getClass为什么迫使我使用扩展?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58515789/

10-10 19:25