I have the following interface:
public interface Caster{
public boolean tryCast(Object value);
}
and its implementations:
public class IntegerCaster{
public boolean tryCast(Object value){
try{
Integer.class.cast(value);
return true;
} catch (ClassCastException e){
return false;
}
}
}
public class DateCaster{
public boolean tryCast(Object value){
try{
Date.class.cast(value);
return true;
} catch (ClassCastException e){
return false;
}
}
}
Is it possible to make such implementation generic? We can't quite take and declare Caster with type parameter, because we won't be able implement it as follows:
public interface Caster<T>{
public boolean tryCast(Object value);
}
public class CasterImpl<T> implements Caster<T>{
public boolean tryCast(Object value){
try{
T.class.cast(value); //fail
return true;
} catch (ClassCastException e){
return false;
}
}
}
You have to inject the Class value, parameterized by T, within your Generic CasterImpl.
Something like this:
public class CasterImpl<T> implements Caster<T> {
private Clazz<T> clazz;
public CasterImpl(Class<T> clazz) {
this.clazz = clazz;
}
public boolean tryCast(Object value){
try{
clazz.cast(value);
return true;
} catch (ClassCastException e){
return false;
}
}
}
As a side note: I don't see a reason why the Caster interface is Generic, since you don't use the type-parameter within the interface.
This can be done without interface at all using standard Class.isInstance method. If you still want to implement this interface, use
public Caster getCaster(final Class<?> clazz) {
return new Caster() {
public boolean tryCast(Object value) {
return clazz.isInstance(value);
}
};
}
Or simpler in Java 8:
public Caster getCaster(final Class<?> clazz) {
return clazz::isInstance;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With