mercredi 30 mai 2018

ClassCastException while using Java Reflection

I'm working with a stub that receives data from the skeleton:

MethodCallMessage reply = messageManager.wReceive();
        String returnString = reply.getParameter("result.string");
        int returnInt = Integer.parseInt(reply.getParameter("result.integer"));
        char returnChar = reply.getParameter("result.character").charAt(0);
        boolean returnBool = Boolean.valueOf(reply.getParameter("result.bool"));
        System.out.println("String return value in Invocation Handler: " + returnString);
        System.out.println("Int return value in Invocation Handler: " + returnInt);
        System.out.println("Char value in Invocation Handler: " + String.valueOf(returnChar));
        System.out.println("Bool value in Invocation Handler: " + String.valueOf(returnBool));

Then I try to create an instance of a class which is in a different package:

Class c = Class.forName(method.getReturnType().getName());
c.newInstance();

I can get to the methods so I thought everything was dandy:

Method[] methods = c.getDeclaredMethods();
        System.out.println("size: " + methods.length);
        for(Method method1: methods){
            System.out.println(method1.getName());
            if(method1.getReturnType().equals(String.class) && method1.getReturnType().toString().startsWith("set")){
                System.out.println("heir");
                method1.invoke(c, returnString);
            }
            if(method1.getReturnType().equals(Integer.class) && method1.getReturnType().toString().startsWith("set")){
                method1.invoke(c, returnInt);
            }
            if(method1.getReturnType().equals(Character.class) && method1.getReturnType().toString().startsWith("set")){
                method1.invoke(c, returnChar);
            }
            if(method1.getReturnType().equals(Boolean.class) && method1.getReturnType().toString().startsWith("set")){
                method1.invoke(c, returnBool);
            }

        }

and at the end of it all I return the object:

return c;

But then I get:

java.lang.ClassCastException: java.lang.Class cannot be cast to be.kdg.distrib.testclasses.TestObject

The package is what I pass trough the Class.forName() . How come I can get to the methods and fields but can cast it?





Aucun commentaire:

Enregistrer un commentaire