简体   繁体   中英

Migrating from Java 7 to Java 8 - compilation error

The following code compiles both test methods using javac in JDK7 but JDK8 will only compile willCompile method.

The error for willNotcompile is: "The method method ( Class<T> ) in the type Klasa is not applicable for the arguments ( Class )."

@Test
public void willCompile() throws InstantiationException, IllegalAccessException {
    Class klass = getObject(Class.class);
    method(klass);
}

@Test
public void willNotCompile() throws InstantiationException, IllegalAccessException {
    method(getObject(Class.class));
}

<T> ResponseEntity<T> method (Class<T> klasa) {
    return new ResponseEntity<T>(HttpStatus.OK);
}
public static <T> T getObject(Class<T> clazz) throws IllegalAccessException, InstantiationException {
    return clazz.newInstance();
} 

The above compiles because it is using rawTypes.

The bottom one doesn't because your method only accepts a Class<T> , but you gave it a Class . Using reflection, you cannot specify the generic types of a class, so getObject will return a raw Class object.

The only fix for the problem is casting the return result.

method((Class<?>)getObject(Class.class));

But while this solution solves the runtime problem you still get problems with the fact that you cannot create new instances of Class .

JDK 7 was less strict in this comparison and casted the return result Class into a Class<?> behind the scenes so the code was allowed to compile.

According to Holger JDK 7 turns off generics types for the whole lines, and uses raw types for the return result, meaning that method gets a Class and returns a ResponseEntity .

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