You know what "import" is in Java, right?
But how do they accurately choose the right classes to import in the first place? And how do they call the methods?
Well if you were to call PrintTagbangers from a Main class, it should look something like this:
Main.java
package com.example.sample2; import java.lang.reflect.Method; public class Main { public static void main(String[] args) throws Exception { PrintTagbangers printTagbangers = new PrintTagbangers(); printTagbangers.print(); } }
PrintTagbangers.java
package com.example.sample1; public class PrintTagbangers { private String companyName = "Tagbangers"; public void print() { System.out.println(companyName); } }
The class that was made first should not be able to know what class could be made in the future!
Then how do they find classes? The answer is: they search classes using the string of the class path.
Here's an example:
Main.java
package com.example.sample2; import java.lang.reflect.Method; public class Main { public static void main(String[] args) throws Exception { Class clazz = Main.class.getClassLoader().loadClass("com.example.sample1.PrintTagbangers"); (Class clazz = Class.forName("com.example.sample1.PrintTagbangers");) Object object = clazz.newInstance(); Method method = clazz.getMethod("print"); method.invoke(object); } }
There's nothing to change for PrintTagbangers.java so I disregarded it.
Here's a description of what the code above does:
1. Generate Class class from the string of the class path. (sounds like rap doesn't it)
2. Instantiate Class class. Same with when assigning a blank argument list for a new operator.
3. Get Method class from the string of the Method name. Method class provides the information and access for the specified method.
4. Run clazz.print method with the invoke method.
We usually don't do this since we have import sentences, but it doesn't hurt to know, right?
Original article written by: Ryosuke Uchitate
Translated by: Yu Koga