jeudi 23 septembre 2021

Java reflection java.lang.ClassNotFoundException. Related to finding the full class name

I am currently trying to develop a method for invoking a specific class. The problem I am having is that I need to get the fully-qualified name or full class name when I invoke the class.

public static void testAlgorithm(String className, String methodName, long n) throws Exception 
{
    Class<?> myClass = null;
    Object myObject = null;
    try {
        
        myClass = Class.forName(className);
        myObject = myClass.newInstance();
        
        Class<?>[] params = new Class[1];
        params[0]=Long.TYPE;
        
        Method m = myClass.getMethod(methodName, params);
        
        m.invoke(myObject, n);
    }catch(Throwable e) {
        System.err.println(e);
    }
}

I call it from main

try {
    testAlgorithm("Algorithms", "linear", 50);      
    } catch (Exception e) {
        e.printStackTrace();
    }

I tried passing different arguments for className and I also directly modified the method inside to try to get the full class name but I didn't get anything to work. I have the class in the same project file Session01 and in the same package as well lab01.

I also checked out a similar question here.

And it leed me to also trying out:

Class currentClass = new Object() {}.getClass().getEnclosingClass();

inside the Algorithms class but I don't get the java.lang.String that I need to use for the method I am working on.





Aucun commentaire:

Enregistrer un commentaire