简体   繁体   中英

Passing Parameters Between ClassLoaders Via Reflection API

I'm using a custom Classloader to create and return an instance of a class, this seems to work ok however when I try to call a method (via the Reflection API) and pass in a custom object as described below I get a NoSuchMethodException :

Supposing that the custom class loader creates and returns an instance like so:

Object obj = customClassLoader.load(String className,Class[] paramTypes,Object[] param)

Then I call a method (via reflection) and pass in a custom object:

NOTE: THIS IS THE LINE CAUSING THE ERROR

Method m = obj.getClass.getDeclaredMethod("mName",new Class[]{aCustomObject.class}) 

m.invoke(obj,new Object[]{new CustomObject() })

I'm stumped as to what could be causing the exception since a method definitely does exist which takes the specified custom object, I have confirmed this by using reflection to list all methods.

How is your custom loader's load() method instantiating the object it is to return? Maybe the NoSuchMethodException arises during trying to find the correct constructor?

This example seems to work out OK:

package com.pholser;

import java.lang.reflect.Method;

public class ClassLoading {
    public static class CustomLoader extends ClassLoader {
        public Object load(String className, Class<?>[] paramTypes, Object[] params) throws Exception {
            Class<?> loaded = loadClass(className);
            return loaded.getConstructor(paramTypes).newInstance(params);
        }
    }

    public static class ACustomObject {
    }

    public void foo(ACustomObject a) {
        System.out.println("foo");
    }

    public static Object newCustomObject() throws Exception {
        return new CustomLoader().load("com.pholser.ClassLoading$ACustomObject", new Class<?>[0], new Object[0]);
    }

    public static void main(String[] args) throws Exception {
        ClassLoading obj = new ClassLoading();

        Method m = obj.getClass().getDeclaredMethod("foo", ACustomObject.class);

        m.invoke(obj, newCustomObject());
    }
}

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