Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
} 
like image 713
user3364192 Avatar asked Feb 05 '16 09:02

user3364192


People also ask

Can I have both Java 7 and 8 installed?

As Cootri has stated - you can install any number of Java versions on windows machines.

Is Java 7 backwards compatible?

The backwards compatibility means that you can run Java 7 program on Java 8 runtime, not the other way around. There are several reasons for that: Bytecode is versioned and JVM checks if it supports the version it finds in . class files.

Is JDK 1.8 is same as JDK 8?

http://www.oracle.com/technetwork/java/javase/jdk8-naming-2157130.html Java SE Development Kit 8, also known as JDK 8, has the version number 1.8. In short – 8 is product version number and 1.8 is the developer version number (or internal version number). The product is the same, JDK 8, anyways.


1 Answers

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.

like image 132
Ferrybig Avatar answered Nov 16 '22 04:11

Ferrybig