Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a Static Method Using a String of the Class's filename in Java

Let's say I use file.list() to get all the files in the src folder. Pretend one filename is called Problem0001.java. Is it possible to call the method of the Problem0001.java class using only the String "Problem0001.java"?

Deeper explaination: I'm working on problems from project Euler. Project Euler are a bunch of problems that require math and programming knowledge. I want each problem to be solved it it's own class. I decided that it would be awesome if I can create a menu where I type in the problem number and the answer shows up on the screen. I started out with a switch statement that would call the class that had the problem solution. I figured eventually I would get sick and tired of adding to the switch statement each time I solved a new problem. I want the computer to find all the solution class files and put the number of the solution in a list (Since I might skip some problems). Whenever I enter the menu screen, the list will be printed out. I type in the number of the solution that I want to see, and this is the part where I'm lost. I somehow need to take that number and call the static method of the class with the same number. So if I type in 3, classfile Problem0003.java will activate, or however the compiler works.

like image 397
nugen.exe Avatar asked Dec 21 '22 08:12

nugen.exe


2 Answers

When you have a class name, you will have to load the class at runtime using ClassLoader to get hold of .class

Class<?> clazz = Class.forName("org.someorg.SomeClass");

Once you have that you can invoke static methods using Reflection

Method method = clazz.getMethod("methodName", String.class);
method.invoke(null,"someString");

Note: Assuming the method takes a string as an argument is String.class

like image 155
Narendra Pathai Avatar answered Feb 25 '23 09:02

Narendra Pathai


Yes, you can, using java Reflection API.

take a look at an example of how to call a method at runtime.

like image 23
codeMan Avatar answered Feb 25 '23 08:02

codeMan