user2954175
user2954175

Reputation: 59

Associating classes with strings

I am currently at a stage in my project where I have a bunch of classes which all sub class one abstract class.

My program asks for input from the user and the way that I want to be able to create objects from these classes is by somehow using the input.

The input is exactly the same as the Class names, for example (if they were to enter "Test" then I would want to create a Test class or if they were to enter "Blah" then I would want to create a Blah class and these two classes as well as all the other classes would subclass one main abstract class.

I am just wondering how I would go about creating these instances of these subclasses from just the input.

Upvotes: 3

Views: 78

Answers (3)

Kraiss
Kraiss

Reputation: 999

There is no generic method you can create to achieve that simply. You will have to test the begin of your input and instantiate "manually" your instance. As instance,

// where input is the input of the user
MyAbsClass newObj = null;
if(input.startsWith("Blah"))
    newObj = Blah.parse(input)
if(input.startsWith("Test"))
    newObj = Test.parse(input)

where parse(String) is a static method which create your instance

Upvotes: 0

Saj
Saj

Reputation: 18712

Class<?> someClass = Class.forName(name_of_the_class);
Constructor<?> someConstructor = someClass.getConstructor(String.class);
Object someObject = someConstructor.newInstance(some_constructor_argument);

Upvotes: 1

Harmlezz
Harmlezz

Reputation: 8078

Try it by using Class.forName():

public class Example {
    public static void main(String[] args) throws Exception {
        Example example = (Example) Class.forName("Example").newInstance();
        example.printMe();
    }

    public void printMe() {
        System.out.println("Hallo");
    }
}

You may have to add your package name, if the classes are not entered with package names and they are not defined in the default package. Perhaps you have to use something else then the default constructor. To few infos so. Its just an example. Hope it helps.

Upvotes: 2

Related Questions