0

Let's say I have 3 classes: GNP_US, GNP_China and GNP_India. I also have a "starter" class, which checks if there is a string in args[0]. This String is either "US","China" or "India". How am I able to dynamically create a new instance of a class depending on the string? I thought maybe something like this:

    public static void main(String[] args)
    {
      try
      {
        Class c=Class.forName("GNP_"+args[0]);
        Object o=c.newInstance();
      }
      catch(Exception e){......} 
    }

But since I have to cast my object into its correct class, I still have to use a lot of if-statements to cast my Objects depending on the "country"-string. Which leaves me with about the same lot of code lines, when I do it like this:

    [...]if(args[0].equals("US")
         {
           GNP_US us=new GNP_US();
         }

I hope you understand where I'm trying to go.

Thanks in Advance!

1
  • 1
    I've edited my answer to address the matter more correct Commented Feb 4, 2014 at 10:19

4 Answers 4

1

Use Class.newInstance for runtime instance creation.

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

Comments

1

Try this:

public static void main(String[] args) throws Exception {
        Class clazz = Class.forName("test.Demo");
        Demo demo = (Demo) clazz.newInstance();
    }

Comments

1

Try this:

public static void main(String a[]) {

    String className = str[0]; // Make sure the class name is correct
    Class c = null;
    try {
        c = Class.forName(className);
        // create instance at runtime
        Object o = c.newInstance();

    } catch (ClassNotFoundException exception) {
        // Handle
    } catch (InstantiationException exception) {
        // Handle
    } catch (IllegalAccessException exception) {
        // Handle
    }

}

Note: This will fail if the classname is incorrect. Please provide class-name along with the package hierarchy.

3 Comments

This is pretty much what I found so far aswell, but I'm trying to avoid an awful long list of if-statements which I'll still have if I'll have to cast my objects to the correct class or am I missing something here?
You have to down cast it to specific type to access class specific methods. Unless you cast it, I dont see any point in creating the instance.
I've edited my answer accordingly. This might make my question more clear!
1

You may use Java Reflections Api. Something like that:

Class c = Class.forName("args[0]");
Object o = c.newInstance();

1 Comment

This does seem right, but after this I'd have to cast my Object statically which would contradict the whole purpose of dynamic, wouldn't it? ;)

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.