简体   繁体   中英

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 . 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.

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. b1.get() is an Object , a1.set() takes an unknown subclass of 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.

Create an Adapter class which transforms your Object B to Object 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

A a = Adapter.adaptTo(b);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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