3

I want to map a String into a Java class. For example, I want to define my Main class such that it works in the following way:

$ java Main SayHello
Hello!
$ java Main SayBye
Bye!
$ java Main SayHola
Error: No such class exists

Here is the code.

public class Main {
    public static void main(String[] args) {
        // Call args[0].say()
    }
}

public class SayHello {
    public static void say() {
        System.out.println("Hello!");
    }
}

public class SayBye {
    public static void say() {
        System.out.println("Bye!");
    }
}

I know that I could do it by manually mapping each possible value of args[0] to a Java class, for example:

if (args[0].equals("SayHello")) {
    SayHello.say();
}

But is there a way to do this automatically?

I Like to Code
  • 7,101
  • 13
  • 38
  • 48

2 Answers2

1

I found an answer here Creating an instance using the class name and calling constructor

Where you can call class by its name

Class<?> clazz = Class.forName(className);
Constructor<?> ctor = clazz.getConstructor(String.class);
Object object = ctor.newInstance(new Object[] { ctorArgument });
Community
  • 1
  • 1
youssefhassan
  • 1,067
  • 2
  • 11
  • 17
1

You can do it like that:

public static void main(String[] args) {
    final String className = "com.my.package." + args[0];
    try {
        Class<?> clazz = Class.forName(className);
        Method method = clazz.getMethod("say");
        Object object = clazz.newInstance();
        method.invoke(object);
    } catch (ClassNotFoundException e) {
        System.err.println("Error: No such class exists");
    } catch (SecurityException e) {
        System.err.println("Error: You are not allowed to do that");
    } catch (NoSuchMethodException e) {
        System.err.println("Error: No such method exists");
    } catch (InstantiationException e) {
        System.err.println("Error: Unable to instantiate");
    } catch (IllegalAccessException e) {
        System.err.println("Error: No access to class definition");
    } catch (IllegalArgumentException e) {
        System.err.println("Error: Illegal argument");
    } catch (InvocationTargetException e) {
        System.err.println("Error: Bad target");
    }
}

Note: as your say() method is static, you can replace:

        Object object = clazz.newInstance();
        method.invoke(object);

by:

        method.invoke(null);
Florent Bayle
  • 11,520
  • 4
  • 34
  • 47