简体   繁体   English

使用自定义类加载器将类转换为对象

[英]Cast class to object with custom classloader

Currently working on a mechanism that allows the deserialization of objects serialized with the Prevayler library. 当前正在研究一种机制,该机制允许对使用Prevayler库序列化的对象进行反序列化。 For example: 例如:

I have old .jar with classes: 我有旧的.jar和类:

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. 现在我需要某种迁移,因为需要将类“ B”中的“ c”强制转换为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? 我与类B相似。我如何将Object obj强制转换为“ B”,以便可以从类B调用方法getC?

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. 您将需要首先检查其类型是否为B,然后将其显式转换为B。请记住,obj变量的类型为Object,但其引用的对象为B,因此getClass()应该返回B。该方法,Object类型的obj参数是您要在其上调用该方法的对象。 It can only be null if the method in question is static. 如果所讨论的方法是静态的,则只能为null。 Otherwise, you will need to specify what instance of class A you wish to invoke the method on. 否则,您将需要指定要在其上调用该方法的类A的哪个实例。

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...) 请参阅此处的调用文档: http : //docs.oracle.com/javase/7/docs/api/java/lang/reflect/Method.html#invoke(java.lang.Object,%20java.lang.Object .. 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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