1

I have to get the class name from user and load it dynamically.

  public class sample{
    public static void main(String[] args) {
    if(args.length < 1)
    {
        print_usage();
    }
    else{
        Class inputClass = null;
        try {
            inputClass = Class.forName(args[0]);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
  }

I have classes named Sample2, Sample3:

public class Sample2 {
    private String name;
}

public class Sample3 {
    private int value;
}

I want to load class based on user input, either Sample2/Sample3 class.

I have the files in the same directory, but I get the java.lang.ClassNotFoundException error. How do I fix this error?

1
  • Your classes are in package? You have added the directory to the classpath? Commented Oct 15, 2015 at 5:54

1 Answer 1

2

Please be more clear on your question, I assume you are typing in the class names without the package.
If they're in a package, you must use Class.forName by that.

Class inputClass = null;
try {
    inputClass = Class.forName("my.package.MyClass");
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! That was the problem. I was not giving the package name.
Is it possible to call the getter/setter/normal methods that are defined in the inputClass? I am only able to get the defined methods using getDeclaredMethods(), but I am not able to define an instance of the inputClass and call the methods passing arguments.
You could try to use newInstance(). But it's really evil.
Method[] methods = inputClass.getMethods(); methods[count].invoke(inputClass.newInstance(),inputString); I get java.lang.InstantiationException. Am I invoking the method right?
I figured what the problem was. I had defined a custom constructor and it seems newInstance() works only if no constructor is defined for the inputClass

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.