This article describes a simple implementation method for Java reflection. Share it for your reference. The specific implementation method is as follows:
The code copy is as follows: package reflect;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
interface fruit{
public abstract void eat() ;
}
class Apple implements fruit{
public void eat() {
System.out.println("eat Apple");
}
}
class orange implements fruit{
public void eat() {
System.out.println("eat orange");
}
}
class init{
public static Properties getPro() throws FileNotFoundException, IOException{
Properties pro = new Properties();
File f = new File("fruit.properties");
if(f.exists()){
System.out.println("There is a configuration file!");
//Read key-value pairs from the configuration file
pro.load(new FileInputStream(f));
}else{
System.out.println("No configuration file!");
pro.setProperty("apple", "reflect.Apple");
pro.setProperty("orange", "reflect.orange");
pro.store(new FileOutputStream(f), "FRUIT CLASS");
}
return pro ;
}
}
class Factory{
public static fruit getInstance(String className){
fruit f = null ;
try {
//Get fruit instance object through reflection
f = (fruit)Class.forName(className).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return f ;
}
}
public class Hello {
public static void main(String[] args) {
try {
Properties pro = init.getPro();
fruit f = Factory.getInstance(pro.getProperty("apple")) ;
if(f != null){
f.eat() ;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The result is:
There is a configuration file!
eat Apple
I hope this article will be helpful to everyone's Java programming.