dimanche 19 juillet 2015

Cast class to subclass

For example. I have hundred or more classes A, B, C... that cannot be changed. Each of these classes have subclasses {A1, A2, ... An}, {B1}, {C1, C2} ... wich I should create depending from its super classes. But most of supers have only one sub

I can see only two variants:

  1. I create hundred factory methods (or constractor) for each class hierarchy to get subclasses. Something like:

    public static <Sub extends A> Sub buildSubClass(A superc) { 
        Sub subclass;
        if(isA1()) {
           subclass = new A1();
           subclass.setField(superc.getField())
           // etc for each field of A class
        } else if(isA2()) {
           subclass = new A2();
           subclass.setField(superc.getField())
           // ....
        } // etc.
        return subclass;
    }
    
    
  2. Can I use reflection

    public static <S, T> T castObject(S source, Class<T> targetClass) {
        T newInstance = targetClass.newInstance();
             for (Field field : source.getClass().getDeclaredFields()) {
                 for (Field fieldTarget : targetClass.getDeclaredFields()) {
                     if (isFieldsEqual(field, fieldTarget)) {
                         setField(getField(field, source), 
                    fieldTarget,  newInstance);
                     }
                 }
             }
             return newInstance;
      }
    
    

Have java more elegant way to cast object to subclass object? Ideal way for me it just change object signature to not create new instances of A subclass but change it so that java consider it as instance of subclass object(with new fields). Something like:

A superc = new A(); 
A1 sub = (A1) superc;

I now it will not work, but I want something in this manner;





Aucun commentaire:

Enregistrer un commentaire