Reputation: 33
I have a code like
private List<xyzClass> fieldName;
public List<xyzClass> getFieldName(){
return fieldName;
}
public void setFieldName(List<xyzClass> abc){
this.fieldName= abc;
}
but when compiled to java byte code, the parameteres are missing as below:
private List fieldName;
public List getFieldName(){
return fieldName;
}
public void setFieldName(List abc){
this.fieldName= abc;
}
This is creating issue with SOAP as not able to typecast to xyzClass Exception.
From Eclipse I see the class file created is good but when I tried command line javac or maven the class file is missing these parameters.
Upvotes: 3
Views: 85
Reputation: 1429
This is as a result of type erasure. Basically java uses the generics to confirm that you are not violating the type constraints during compile time. All the generics are then removed and replaced with the highest class in the inheritance hierarchy. This will default to Object
but if you say <T extends ParentClass>
(for example) the T
generics will be replaced with ParentClass
.
Upvotes: 6
Reputation: 4998
This is called Type Erasure.
Any objects that make use of generics are compiled with bounds. This provides a way to make code "type-safe." As Java is a statically typed language, all variables must be defined beforehand. This provides a method to prevent casts that may result in exceptions, most notably ClassCastException
s. Any type parameter is replaced with Object. Like so:
Source code:
public class Hi<Type>
{
public void sayHi(Type t)
{
...
will be compiled to...
public class Hi<Type>
{
public void sayHi(Object t)
{
...
This of course varies when you impose a restriction on the generic, most notably when using the extends
keyword. For example:
public class Hi<Type extends Number>
{
public void sayHi(Number t)
{
...
Upvotes: 2