本文介绍了Java泛型,获得Class< T>通用参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象类:

  public abstract class RootProcessor< T> {
Class< T> clazz中;
}

我需要填写 ClassT clazz; RootProcessor 的子元素 - 每个孩子都有自己的 T



我只找到了一个解决方案,但它需要编译器参数 -Xlint:unchecked



<$ p $(){()}()()(){getClass()} getActualTypeArguments()[0];
}

这是最佳解决方案吗?没有 -Xlint:unchecked

解决方案

类型安全的,但是可以这样做的方法是在编译器可以看到它的地方传递 Class< T> 标记:

  public abstract class RootProcessor< T> {
Class< T> clazz中;

protected RootProcessor< T>(Class< T> clazz){
this.clazz = clazz;
}
}

公共类FooProcessor扩展了RootProcessor< Foo> {
public FooProcessor(){
super(Foo.class);




$ b $ p
$ b如果你正在做一个未经检查的转换,知道你在做什么,并希望编译器停止抱怨,正确的方法是将非类型安全但是你知道他们工作的位本地化,并使用 @SuppressWarnings

  public abstract class RootProcessor< T> {
Class< T> clazz中;
{initClazz(); }

@SuppressWarnings(unchecked)
private void initClazz(){
//您在问题中已经有的常用语言
this.clazz = this 。.getClass()getGenericSuperclass()yadda()等等()。;


$ / code $ / pre

(我不会对此持反对意见:P )

I have an abstract class:

public abstract class RootProcessor<T> {
    Class<T> clazz;
}

I need to fill ClassT clazz; with the children of RootProcessor - every child has its own T

I found only one solution, but it needs compiler argument -Xlint:unchecked

public RootProcessor(){
    this.clazz = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}

Is this the best solution? Can we do the same without -Xlint:unchecked ?

解决方案

The typesafe, but boilerplatey way to do this is to pass the Class<T> token "where the compiler can see it":

public abstract class RootProcessor<T> {
    Class<T> clazz;

    protected RootProcessor<T>(Class<T> clazz) {
        this.clazz = clazz;
    }
}

public class FooProcessor extends RootProcessor<Foo> {
    public FooProcessor() {
        super(Foo.class);
    }
}

If you're doing an unchecked cast but you "know what you're doing" and want the compiler to stop complaining, the correct approach would be localising the non-type-safe-but-you-know-they-work bits and using @SuppressWarnings:

public abstract class RootProcessor<T> {
    Class<T> clazz;
    { initClazz(); }

    @SuppressWarnings("unchecked")
    private void initClazz() {
        // the usual verbiage you already have in your question
        this.clazz = this.getClass().getGenericSuperclass().yadda().blah();
    }
}

(I won't hold this against you :P)

这篇关于Java泛型,获得Class&lt; T&gt;通用参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 02:53