用非泛型实现覆盖泛型方法 [英] Overriding generic methods with non-generic implementations

查看:138
本文介绍了用非泛型实现覆盖泛型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如果我有 ClassA< T> ,我可以用一个引用具体类的子类来覆盖它,比如 ClassB extends ClassA< String> ,然后ClassA使用T的任何地方,ClassB可以使用String 。
$ b

现在,忽略前面的 ClassA ClassB ,如果我有一个抽象 ClassA ,它有一个通用的方法:

  public< T> void doSomething(T data); 

有什么办法可以有一个 ClassB 用一个具体的类来覆盖它,类似于前面的例子?我已经想出了一些可行的方法,即对类和方法进行参数化,但是我想知道是否有其他方法。

  class ClassA< T> {
public void doSomething(T data){};
}

我不想在类中放置参数的原因是因为只有一种方法可以处理这种类型的任何内容,而某些子类可能甚至不想在该方法中做任何事情,所以如果不打算使用它,则不需要在类中放入参数。


$ b

注意 ClassA 的所有子类都是匿名类,因此增加了趣味性。 感谢 type erasure ,this:

  public< T> void doSomething(T data); 

真正的意思是:

  public void doSomething(Object data); 

所以不行,没有办法用更严格的参数类型重写。



在此代码中:

  class ClassA< T> {
public< T> void doSomething(T data){};

$ / code>

类名中的类型参数和方法中的类型参数实际上是不同的参数。这就像在更高的范围内声明与变量相同名称的局部变量。您可以在 ClassA< String> 的实例上调用 doSomething(123),因为第二个 T 是本地方法。


I'm experimenting with generics in Java, and thought of this example.

If I have ClassA<T>, I can override it with a subclass that references a concrete class, such as ClassB extends ClassA<String>, then anywhere ClassA uses T, ClassB can use a String.

Now, ignoring the previous ClassA and ClassB, if I have an abstract ClassA, which has a generic method:

public <T> void doSomething(T data);

Is there any way I can have a ClassB that overrides it with a concrete class, similar to the previous example? I've come up with something that works, which is to parameterize both the class and the method, but I'm wondering if there's another way.

class ClassA<T> {
    public void doSomething(T data) {};
}

The reason I don't want to put the parameter in the class is because it's only one method that does anything with that type, and some subclasses may not even want to do anything in that method, so I shouldn't need to put a parameter in the class if it's not going to use it.

NOTE: All of the subclasses of ClassA are anonymous classes, so that adds to the fun.

解决方案

Thanks to type erasure, this:

public <T> void doSomething(T data);

Really means this:

public void doSomething(Object data);

So no, there isn't a way to override with a more restrictive parameter type.

Also in this code:

class ClassA<T> {
    public <T> void doSomething(T data) {};
}

The type parameter in your class name and the type parameter in the method are actually different parameters. It's like declaring a local variable of the same name as a variable in a higher scope. You can call doSomething(123) on an instance of ClassA<String> because the second T is local to the method.

这篇关于用非泛型实现覆盖泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆