Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Reflection, Class Objects

My objective is to read in to the command line the name of a Class I wish to observe info on. When I know the class name before runtime, I have no issue. What I can't seem to manage is how to create a class object based on a string input.

public class Tester {

    static void methodInfo2(Object obj) throws ClassNotFoundException {
        //some stuff        
        System.out.print("Test!");

    }

    public static void main (String args[]) throws ClassNotFoundException{
        String className = args[0];
        System.out.println("Class:  "+className);

        //myclass2 mc = new myclass2();
        //Class c = mc.getClass();
        Class argClass = Class.forName(className);

        try {
            methodInfo2(argClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


    }

}

The 2 commented out lines in the main method show what I have done in the past when I know the class name before I compile. The following uncommented line shows what I thought should work, but I receive a ClassNotFoundException. The class certainly exists so I'm not sure what problem I'm having.

like image 948
Nibirue Avatar asked Feb 01 '26 05:02

Nibirue


2 Answers

Two suggestions:

  1. Make sure you're giving it the fully-qualified name (e.g. "java.lang.Thread" and not just "Thread").
  2. Make sure the compiled class file is actually on the classpath.
like image 82
NPE Avatar answered Feb 03 '26 23:02

NPE


Class.forName is the right way to load a class by name at runtime.

Either your argument is wrong or your class isn't in the classpath.

like image 30
wrschneider Avatar answered Feb 04 '26 00:02

wrschneider



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!