Unexpected generic behavior

I found weird generic behavior. In a nutshell - the thing I really want is to use ComplexObject1 in the most general way, and the thing I really missed is why a certain generic type (... extends BuisnessObject) is lost. A discussion of the topic is also available on my blog http://pronicles.blogspot.com/2010/03/unexpected-generics-behaviour.html .

public class Test {

  public interface EntityObject {}

  public interface SomeInterface {}

  public class BasicEntity implements EntityObject {}

  public interface BuisnessObject<E extends EntityObject> {
    E getEntity();
  }

  public interface ComplexObject1<V extends SomeInterface> extends BuisnessObject<BasicEntity> {}

  public interface ComplexObject2 extends BuisnessObject<BasicEntity> {}

  public void test(){
    ComplexObject1 complexObject1 = null;
    ComplexObject2 complexObject2 = null;

    EntityObject entityObject1 = complexObject1.getEntity();
    //BasicEntity entityObject1 = complexObject1.getEntity(); wtf incompatible types!!!!
    BasicEntity basicEntity = complexObject2.getEntity();
  }
}
+3
source share
2 answers

Your problem is that you are using a raw type ComplexObject1. This is easy to fix: just use it ComplexObject1<?>instead and your code compiles fine.

.

tutorial:

, . , .

JLS 4.8 ():

raw . , Java, . , Java .

. Java 2nd Edition, Item 23: raw- .

+2

, , . .

. ?

raw?

.

- , Collection, .

, ?

, .

. :

public interface MyClass<T> {
  T foo();
  List<String> bar();
}

MyClass m = ...
List<String> list = m.bar(); // warning!

, generic type, , Java.

+1

Source: https://habr.com/ru/post/1736952/


All Articles