Sharath Bhaskara
Sharath Bhaskara

Reputation: 497

Clarification on Generic Type Erasure in java code compilation

Problem: After the parameterized type is compiled and when the class is referenced by a jar, the client is forced to create raw types as the compiler does type erasure.

For Example:

public class GenericFeature<T>{
  T object;
  public void dosomething(){
    // do something
  }
}

After compiling and adding it as a dependency in another application, the user is not able to use the Parameterized type.

GenericFeature<Integer> intFeature = new GenericFeature<Integer>() // is erroring out saying GenericFeature is not parameterized type.

Analysis I did read about the type erasure of generics in compilation, as it states that my example parameterized type will be looking as given below after compilation.

public class GenericFeature{
  Object object;
  public void dosomething(){
    // do something
  }
}

Quesion: If this is how the type erasure happen, then how do the Java's internal objects like Comparable<T>, Class<T> retain their parameterized constructs.

May be I am missing something very basic, please excuse and educate me in such case.

Upvotes: 2

Views: 50

Answers (2)

Sharath Bhaskara
Sharath Bhaskara

Reputation: 497

Looks like there is no problem, with the type erasure. Sorry for misleading, after spending some time analyzing the issue, found out that there is some maven configuration issue in the project where my GenericFeature<T> is defined. I am able to retain the type if I move this class to a different project.

Analyzing, more on what was that configuration that created this issue, if i find something then I will post that in my answer.

Upvotes: 0

leeor
leeor

Reputation: 17751

Take the <T> off the class declaration, that is why you cannot use it. This should work:

public class GenericFeature<T>{
  T object;
  public void dosomething(){
    // do something
  }
}

Upvotes: 2

Related Questions