0

Is there any way to get this to work

String ClassName = "testing";
Classname.main();

testing.class is a class in the bin folder
if its important I'm using eclipse

  • 2
    does String have `main()` method? No. – zubergu Dec 14 '15 at 12:02
  • 1
    You can make this work (just not as displayed in your question but in a slightly different way), the keyword here is reflection. Look at the `Class` class and which methods it provides. – Thomas Dec 14 '15 at 12:04

2 Answers2

0

You can do something like this:

String aux = (String) (Class.forName("java.lang.String")).newInstance();

Then you can do what you want with aux, for example calling a static method.

malaguna
  • 4,183
  • 1
  • 17
  • 33
0

you can get the class like this:

public Object withName(String className) {

    try{
        Class<?> c = Class.forName(className);
        Constructor<?> cons = c.getConstructor();

        return cons.newInstance();
    }catch (Exception e){
        e.printStackTrace();
        return null;
    }
}

if you don't know which class it is,to find methods of desired class you can check this post:

Can I get all methods of a class?

Community
  • 1
  • 1
nafas
  • 5,283
  • 3
  • 29
  • 57