为什么Java的Method类不通用?

时间:2022-07-15 20:45:14

That would allow the invoke method to have the right return type. For instance:

这将允许invoke方法具有正确的返回类型。例如:

class Method<T> {
    T invoke(Object obj, Object... args);
}

2 个解决方案

#1


In Java, Generics are only available at compile time. You cannot determine the Generic type at runtime. This allowed the generics implementation to be backwards compatible with old versions of the JVM.

在Java中,泛型仅在编译时可用。您无法在运行时确定Generic类型。这允许泛型实现向后兼容旧版本的JVM。

Since generics are only available at compile time, if you know the type of your class then you do not need to use reflection.

由于泛型仅在编译时可用,如果您知道类的类型,则不需要使用反射。

#2


It would have been not unreasonable to make Method generic on erased return type. However, it would be a lot of effort with little gain. The nature of reflection is that you don't know the types at compile-time - otherwise you could statically link.

在擦除的返回类型上使用Method通用是不合理的。然而,这将是很多努力而收益甚微。反射的本质是你在编译时不知道类型 - 否则你可以静态链接。

I guess you could in some case even add new APIs so that the generic type is returned. The information is still on the method, although not from the instance that you pass to it.

我想在某些情况下你甚至可以添加新的API,以便返回泛型类型。信息仍然在方法上,但不是来自传递给它的实例。

#1


In Java, Generics are only available at compile time. You cannot determine the Generic type at runtime. This allowed the generics implementation to be backwards compatible with old versions of the JVM.

在Java中,泛型仅在编译时可用。您无法在运行时确定Generic类型。这允许泛型实现向后兼容旧版本的JVM。

Since generics are only available at compile time, if you know the type of your class then you do not need to use reflection.

由于泛型仅在编译时可用,如果您知道类的类型,则不需要使用反射。

#2


It would have been not unreasonable to make Method generic on erased return type. However, it would be a lot of effort with little gain. The nature of reflection is that you don't know the types at compile-time - otherwise you could statically link.

在擦除的返回类型上使用Method通用是不合理的。然而,这将是很多努力而收益甚微。反射的本质是你在编译时不知道类型 - 否则你可以静态链接。

I guess you could in some case even add new APIs so that the generic type is returned. The information is still on the method, although not from the instance that you pass to it.

我想在某些情况下你甚至可以添加新的API,以便返回泛型类型。信息仍然在方法上,但不是来自传递给它的实例。