简体   繁体   English

Java中的通用方法,确定类型

[英]Generic method in Java, determine type

I would like to be able to detirmine the return type of my method call at runtime, but I can not seem to be able to get the Type of T. 我希望能够在运行时确定方法调用的返回类型,但似乎无法获得T的类型。

    public <T> T getT()
    {
        Object t = null;
        Class<?> c = t.getClass();
        System.out.println(c.getName());
        return (T) t;
    }

Is there any way to determine the Type of T at runtime in Java? 有什么方法可以在Java运行时确定T的类型吗?

Your function will throw a NullPointerException, because you call "getClass" on a null pointer (since t is initialized with null). 您的函数将引发NullPointerException,因为您在空指针上调用“ getClass”(因为t初始化为空)。 Additionally, generics are used for giving added compile-time type-checking. 此外,泛型用于提供附加的编译时类型检查。 They do not give you anything special at runtime; 它们在运行时不会给您任何特别的东西。 generics simply use type Object, but cause the code which uses the generic object to perform implicit casts and also causes the compiler to be aware of how you will use it. 泛型仅使用对象类型,但是使使用该泛型对象的代码执行隐式强制转换,并使编译器了解您将如何使用它。

Java generics are a static type checking feature. Java泛型是静态类型检查功能。 Attempting to retrieve reflection artifacts from generic parameters is typical of poorly thought out design. 尝试从通用参数检索反射伪像是经过深思熟虑的设计的典型特征。

In the question example, there is no guarantee that T is a class or even interface. 在问题示例中,不能保证T是类甚至接口。 For example 例如

List<? extends Frogs> list = thing.getT();

If you really want to go down this path (and I strongly suggest you don't, not that I expect you to take any notice), then you can supply a reflection object that is statically related to the generic parameter as an argument: 如果您真的想走这条路(我强烈建议您不要这样做,不是我希望您注意一下),那么您可以提供一个与泛型参数静态相关的反射对象作为参数:

 public <T> T getT(Class<T> clazz) {
     Object value = map.get(clazz);
     return clazz.cast(value);
 }

If you have a generic Class you can write a constructor that takes the type and saves it into a member of your class. 如果您有通用类,则可以编写一个构造函数,该构造函数接受类型并将其保存到类的成员中。 This way you can check the Type during runtime. 这样,您可以在运行时检查类型。 All information that are only in the generics are gone after compiling. 编译后,仅泛型中的所有信息都消失了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM