简体   繁体   English

Java 泛型类型非静态方法返回 Object 而不是泛型类型 T

[英]Java Generic Type non-static method return Object instead of generic type T

public class Module<T> {

    @SuppressWarnings("unchecked")
    public <T> T module(Class<T> clazz) {
        return clazz.cast(this);
    }
        
}

This is the base class of my module and I want to initialize it to TestModule by calling the module method above.这是我的模块的基础 class,我想通过调用上面的模块方法将其初始化为 TestModule。

TestingModule testingModule = new Module().module(TestingModule.class);

However, the return type of但是,返回类型

new Module().module(TestingModule.class)新模块().module(TestingModule.class)

is Object instead of TestingModule.是 Object 而不是 TestingModule。 Is there any idea that I can directly initialize it without using any casting or changing the method to static ?有没有什么想法可以直接初始化它而不使用任何转换或将方法更改为static

There are a few problems.有几个问题。 The one most directly linked to the type mismatch error is here:与类型不匹配错误最直接相关的一个是:

TestingModule testingModule = new Module().module(TestingModule.class);

new Module() is using Module without any type argument. new Module()使用Module没有任何类型参数。 When you use a raw type like this, you lose all generic information in the expression.当您使用这样的原始类型时,您会丢失表达式中的所有通用信息。 You can fix it simply by adding a type argument:您可以简单地通过添加类型参数来修复它:

TestingModule testingModule = new Module<String>().module(TestingModule.class);

In the above code, I've added <String> to the constructor call, which resolves the problem.在上面的代码中,我在构造函数调用中添加了<String> ,从而解决了问题。 But String is as strange a type argument as it can get in this case, which leads to the following side note.但是在这种情况下, String是一个很奇怪的类型参数,这导致了下面的旁注。

The declaration public <T> T module(Class<T> clazz) adds a type variable T that hides the class-level type variable of the same name.声明public <T> T module(Class<T> clazz)添加了一个类型变量T ,它隐藏了同名的类级别类型变量。 If this method is not made generic by accident, please use a different name for this variable, and use it .如果这个方法不是偶然的,请给这个变量使用一个不同的名字,然后使用它 Otherwise, this method doesn't need to be generic.否则,此方法不需要是通用的。

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

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