How to access java class method from different maven project using class loader

Viewed 32

trying to access a java class method from different maven project using class loader. able to load and retrieve all the methods available in the respective class. but, it's not invoking the method.

my code snippet.

File file = new File("/sr/main/java/");
     try {
        URL url = file.toURI().toURL();
        URL[] urls = new URL[]{url};
        Object obj = null;
        
        ClassLoader cl = new URLClassLoader(urls);
        Class<?> cls = cl.loadClass("userDefineKeywords");
        
        obj = cls.getDeclaredConstructor().newInstance();
        
        Object[] args1 = null;
        
        Method[] methods =cls.getDeclaredMethods();

        for(int i=0; i<methods.length;i++) {
            if(methods[i].getName().contentEquals("printMsg")) {
                //obj =methods[i].getDeclaringClass();
                methods[i].invoke(obj, args1);
                System.out.println(methods[i].isAccessible());
            }   
        }
    } catch (MalformedURLException | ClassNotFoundException | IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Calling class:

public class userDefineKeywords { 
public void printMsg() {
    System.out.println("the invoking class");
}

}

something making obj to null here:

public Object invoke(Object obj, Object[] args)
    throws IllegalArgumentException, InvocationTargetException
{
    // We can't inflate methods belonging to vm-anonymous classes because
    // that kind of class can't be referred to by name, hence can't be
    // found from the generated bytecode.
    if (++numInvocations > ReflectionFactory.inflationThreshold()
            && !ReflectUtil.isVMAnonymousClass(method.getDeclaringClass())) {
        MethodAccessorImpl acc = (MethodAccessorImpl)
            new MethodAccessorGenerator().
                generateMethod(method.getDeclaringClass(),
                               method.getName(),
                               method.getParameterTypes(),
                               method.getReturnType(),
                               method.getExceptionTypes(),
                               method.getModifiers());
        parent.setDelegate(acc);
    }

    return invoke0(method, obj, args);
}

Thanks!

0 Answers
Related