简体   繁体   中英

Java. How can I upcast type use reflection?

I have a two classes UpObj and DownObj

public class UpObj {

    public UpObj() {
        System.out.println("Load UpObj ");
    }

}

public class DownObj extends UpObj {

    public DownObj() {
        System.out.println("Load DownObj ");
    }

}

public class Caller {

    UpObj obj;

    public Caller(UpObj obj) {
        this.obj = obj;
        System.out.println("!!!");
    }

}

public class GNUMakeFile {

    /**
     * @param args
     */
    public static void main(String[] args) {
        DownObj iView = new DownObj();
        Class<?> iViewClass = iView.getClass();
        Class<?> clazz;
        try {
            clazz = Class.forName("bla.bla.bla.Caller");
            Constructor<?> ctor = clazz.getDeclaredConstructor(iViewClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

    }

}

So, I want upcast my child type DownObj to parent UpObj in Caller constructor. I think this is possible with help generics. Something like this . Anybody know how exactly this use.

Thanks.

There is no standard way doing it. Try to google for some solutions, eg http://www.xinotes.org/notes/note/1329/ or How to get parameter types using reflection? . As I remember the Spring and some other libraries have similar util functions to do it. Do you use the Spring?

You shouldn't really be using Class.getConstructor() with the runtime type of what you want to pass to it – the method works off the formal parameters.

If you need to search for a constructor that matches some objects that you have, you'll have to loop over getConstructors() , inspect the formal parameters of each constructor, and check whether you found a suitable signature using Class.isAssignableFrom() . I don't think there's a convenient way to have the reflection API do overload resolution for you.

(Alternatively, rethink your approach so messing with reflection is no longer necessary.)

I didn't really understand the problem - upcasting is normally not needed.
but it seams like the problem is to get the upper class of the object,
if use the getSuperclass method:

    Constructor<?> ctor = clazz.getDeclaredConstructor(iViewClass.getSuperclass());

Documentation: getSuperclass()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM