0

I'm trying to write a console program that will ask the user for the name of a class. It will take this class name, load it - then create an instance of it so I can invoke methods etc etc.

How would I go about doing this?

So far I have used a Scanner to get the input. But now that I have the class name as a string. I'm not too sure how to load it then create an instance of it.

Any help would be appreciated.

3 Answers 3

3

This question depends on whether the class exists within current classpath context of the application or not.

If it does, then it's a simple case of using something like...

String nameOfClass = ...;
Class classOfName = Class.forName(nameOfClass);
Object instance = classOfName.newInstance();

(nb: These throw a series of exceptions which you will be expected to catch).

Take a closer look at java.lang.Class for more details

If the class does not exist within the current class loader context, then you are going to need to create your own class loader and load the class into and use the class loader to load and create instances of the class

Take a closer look at java.lang.ClassLoader and java.net.URLClassLoader for more details...

Sign up to request clarification or add additional context in comments.

Comments

3
Class myClass = Class.forName(userInputString);
Object o = myClass.newInstance();

Of course you will cast o to the class you want. See Class for more details.

6 Comments

Didn't know about that forName() method! Very helpful, thanks a lot.
Just a note, you can't name your variable class (as it is a reserved word)
Great point. I'm not so bright sometimes. Made the change. Thanks.
@Vidya You missed a variable name ;)
@Vidya Welcome to my world ;)
|
0

You can use Class.forName()

Class someClass = Class.forName(your_class_name)  //must be with package.
Object o = someClass.newInstance();

You can read more about it here

1 Comment

If I need to use methods such as getFields() and getMethods(), I dont need the instance of it right? I just need the Class variable?

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.