subbu royal
subbu royal

Reputation: 624

How to resolve "Type miss match error"

I have two classes one is MyProduct shown below

@Entity
 public class MyProduct extends ProductImpl implements Serializable{
 .......
 ......
 }

and second one is ProductStore

@Component
public class ProductStore extends AbstractRowLevelSecurityProvider{
@Override
 public Class<Serializable> getFetchRoot(AdminUser  user,Class<Serializable> ser, List<FilterMapping> filter){

 return MyProduct.class;//compile time error
 }

but I am getting an compile time error saying

 cannot cast from Class<MyProduct> to Class<Serializable> 

I tried many ways to solve this, but still getting an error can any one help me how to solve this error

Upvotes: 1

Views: 128

Answers (3)

Peter
Peter

Reputation: 5174

If you return Class<Serializable> that you should return exactly that class type. If you want to return a class type that extends Serializable than you should declare you method that way.

Use Class<? extends Serializable> instead of Class<Serializable>.

In case you cannot change the method signature in the super class. Use raw types like:

public class TestSer implements Serializable {

}

@SuppressWarnings("unchecked")
public Class<Serializable> getFetchRoot () {
  Class testSerClass = TestSer.class;
  return testSerClass;
}

Upvotes: 0

public Class getFetchRoot(AdminUser user,Class ser, List filter){

return MyProduct.class;//compile time error

In the above method the return type is Class<Serializable> but you are returning MyProduct.class;.

This is effectively equivalent to Class<Serializable> = MyProduct.class;.

This doesn't work. The problem is Generics does not support sub-typing .

Quoting from the https://dzone.com/articles/5-things-you-should-know-about-java-generics

For ex: we cannot have List<Number> list = new ArrayList<Integer>().

Reason:

The piece of code shown above will not compile because if it compiles than type safety can't be achieved. To make this more clear, lets take the following piece of code shown below where at line 4 we are assigning a list of long to a list of numbers. This piece of code does not compile because if it could have compiled we could add a double value in a List of longs. This could have resulted in ClassCastException at runtime and type safety could not be achieved.

List<Long> list = new ArrayList<Long>();
list.add(Long.valueOf(1));
list.add(Long.valueOf(2));
List<Number> numbers = list; // this will not compile
numbers.add(Double.valueOf(3.14));

To make it work you can either the method return type as Class<MyProduct> or Class<? extends ProductImpl> or Class<? extends Serializable>.

Refer to the above link for more information and limitations.

Upvotes: 1

You have a typo here:

public class MyProduct extends ProductImpl implements Serialazable

You have to use Serializable instead of Serialazable.

Upvotes: 1

Related Questions