Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method for types

Tags:

java

generics

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;
        }
   }
}
like image 963
St.Antario Avatar asked Feb 13 '26 01:02

St.Antario


2 Answers

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.

like image 191
Konstantin Yovkov Avatar answered Feb 14 '26 14:02

Konstantin Yovkov


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;
}
like image 39
Tagir Valeev Avatar answered Feb 14 '26 13:02

Tagir Valeev