This article illustrates a simple Java reflection implementation method. Share to everyone for your reference. The implementation methods are as follows:
Copy Code code 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 the 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 {
To get fruit instance objects by 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 results are:
There are configuration files!
Eat Apple
I hope this article will help you with your Java programming.