简体   繁体   English

Java泛型和通配符

[英]Java generics and wildcards

Let's say I have these classes: 假设我有以下课程:

class A<T> {
  void set(T t) {}
}

class B<T> {
  T get() { return null; }
}

class C extends A<String> { }
class D extends B<String> { }

class E extends A<Long> { }
class F extends B<Long> { }

And these variables: 这些变量:

A<?> a1 = new C();
B<?> b1 = new D();

A<?> a2 = new E();
B<?> b2 = new F();

Can I do these somehow (with some magic?): 我能以某种方式(用魔法来做)吗?

a1.set(b1.get());
a2.set(b2.get());

No. But you can do 不,但是你可以做

A<String> a1 = new C();
B<String> b1 = new D();

A<Long> a2 = new E();
B<Long> b2 = new F();

a1.set(b1.get());
a2.set(b2.get());

A<?> means A of some class, but I don't know which one . A<?>表示某类的A,但我不知道哪一个 So you can't call its set() method because the compiler doesn't know if the type of the argument matches with the actual generic type of A. 因此,您不能调用其set()方法,因为编译器不知道参数的类型是否与A的实际泛型类型匹配。

You cannot because you have 你不能因为你有

A<?> a1 = new C();
B<?> b1 = new D();

is the same as 是相同的

A<? extends Object> a1 = new C();
B<? extends Object> b1 = new D();

So the generic type of a is a wildcard or unknown. 因此, a的通用类型是通配符或未知。 b1.get() is an Object , a1.set() takes an unknown subclass of Object. b1.get()是一个Object ,a1.set()接受Object的未知子类。

A<String> a1 = new C();
B<String> b1 = new D();
a1.set(b1.get()); // is okay as the type is `String`

You want to transform 1 kind of object to another object. 您想要将一种对象转换为另一个对象。 Try adapter pattern . 尝试使用适配器模式 Please check the wiki link for more inside to adapter pattern. 请检查Wiki链接以了解适配器模式的更多信息。

Create an Adapter class which transforms your Object B to Object A. 创建一个Adapter类,将您的对象B转换为对象A。

class MyAdapter
{


public static A adaptTo(B b)
{
//your code to transform B to A

}

}

Now when you want to transform B to A, simply call 现在,当您要将B转换为A时,只需调用

A a = Adapter.adaptTo(b);

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

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