简体   繁体   中英

Cast class to object with custom classloader

Currently working on a mechanism that allows the deserialization of objects serialized with the Prevayler library. For example:

I have old .jar with classes:

class A {
   public B b;
   public B getB() {
       return b;
   }
}

class B {
   public int c;
   public int getC() {
       return c;
   }
}

Now I need some kind of migration, because "c" from class "B" need to be cast for example to String.

I'm using custom classloader to load classes and methods:

    // 1. make List of URLs to pass to CustomClassLoader class
    URL url = new URL(PATH_TO_JAR);
    List<URL> urls = new ArrayList<URL>();
    urls.add(url);

    // 2. Use CustomLoaderClass, to make sure, that loaded classes/methods are not from current project,
    // but from the jar specified in URL, since Java class loaders (including URLClassLoader)
    // first ask to load classes from their parent class loader.
    CustomClassLoader clsLoader = new CustomClassLoader(urls);
    java.lang.Class cls = clsLoader.loadClass("A");

    // String.class in methods second parametr means, that we should pass String to that method
    Method method = cls.getMethod("getB");

    // 3. invoke method which returns Object instead "B"
    Object obj = method.invoke(null);

I've similary done this with class B. How I can cast Object obj to "B" so I can invoke method getC from class B?

You wont be able to specify the type on the left hand side of the assignment operator dynamically. At least I know of no way to do that. You will need to check if its a B type first, then explicitly cast it to B. Remember that the obj variable is of type Object, but the object it references is a B, so a getClass() should return B. When you invoke the method, the obj parameter of type Object is the object you want to invoke the method on. It can only be null if the method in question is static. Otherwise, you will need to specify what instance of class A you wish to invoke the method on.

See the invoke doc here: http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Method.html#invoke(java.lang.Object,%20java.lang.Object...)

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