-2
class Start
{
  public static void main( String[] argv ) 
  {
      int argc =argv.length;
      if ( argc == 0 ) {
          System.err.println( "error");
          return;
      }

      try 
      { 
          Class<?> c = Class.forName( argv[argv.length-1] );
          //c kowalski = c.newInstance( );   
      }
      catch ( Exception e ) { System.out.println(e) ; return; }
    }
}
class Test implements InfoInterface
{
    public void display()
    {
        System.out.println("HI!");      
    }
    static int w;
    public int dodawanie (int a, int b)
    {
        w=a+b;
        return w;
    }
}

My problem is how can I create the object of Test class in Start class?
The Test class has to be added by command line.
In this program I have to get methods from Test class via object in Start class.

Vogel612
  • 5,620
  • 5
  • 48
  • 73
MSB MSB
  • 13
  • 1
  • 5
  • 4
    What's wrong with just calling `c.newInstance()` ? – Mureinik Dec 21 '14 at 15:04
  • 1
    It's not exactly clear what you want. If you want the names of the methods, you can get them from the `Class` object you refer to as `c`. Or do you want to actually *invoke* the methods? – RealSkeptic Dec 21 '14 at 15:07
  • possible duplicate of [Create new class from a Variable in Java](http://stackoverflow.com/questions/1268817/create-new-class-from-a-variable-in-java) – Joe Jan 01 '15 at 06:41

2 Answers2

2

You can create dynamic object by just passing the name of the class with complete class path in the argument while executing the program from command line.

Bhavik Ambani
  • 6,557
  • 14
  • 55
  • 86
0

You can get a new class instance by performing:

Class<?> c = Class.forName(argv[argv.length-1]);
Test t = (Test) c.newInstance( );   

or, if you have more InfoInterface implementations:

Class<?> c = Class.forName(argv[argv.length-1]);
if (!InfoInterface.class.isAssignableFrom(c)) {
    throw new Exception("Invalid interface specified");
}
Class<InfoInterface> iic = (Class<InfoInterface>) c;
InfoInterface ii = iic.newInstance();   

Beware that you specify the full class name (including package name) in the argument used inside of your

Class<?> c = Class.forName(argv[argv.length-1]);

line. You can of course also add the package string yourself:

String command = argv[argv.length-1];
Package p = InfoInterface.class.getPackage();
if (p != null) {
    command = p.getName() + "." + command;
}
Class<?> c = Class.forName(command);

assuming that the Test and other commands are in the same package as InfoInterface.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263