反射java
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import java.lang.reflect.Constructor; class Person { public Person() { } public Person(String name) { this.name = name; } public Person(int age) { this.age = age; } public Person(String name, int age) { this.age = age; this.name = name; } public String getName() { return name; } public int getAge() { return age; } @Override public String toString() { return "[" + this.name + " " + this.age + "]"; } private String name; private int age; } public class reflection { public static void main(String[] args) { Class<?> demo = null; try { demo = Class.forName("reflectAndGeneric.Person"); } catch (Exception e) { e.printStackTrace(); } Person per1 = null; Person per2 = null; Person per3 = null; Person per4 = null; // 取得全部的构造函数 Constructor<?> cons[] = demo.getConstructors(); try { for (int i = 0; i < cons.length; i++) { System.out.println(cons[i]); } per1=(Person)cons[2].newInstance(); per2=(Person)cons[3].newInstance("Rollen"); per3=(Person)cons[1].newInstance(20); per4=(Person)cons[0].newInstance("Rollen",20); } catch (Exception e) { e.printStackTrace(); } System.out.println(per1); System.out.println(per2); System.out.println(per3); System.out.println(per4); } }
getConstructors()得到的构造器顺序好奇怪,和定义的顺序不同。把cons[]数组的下标改成对应的构造器顺序。
输出结果:
public Person(java.lang.String,int)
public Person(int)
public Person()
public Person(java.lang.String)
[null 0]
[Rollen 0]
[null 20]
[Rollen 20]
public Person(int)
public Person()
public Person(java.lang.String)
[null 0]
[Rollen 0]
[null 20]
[Rollen 20]
2.读取properties文件属性+反射工厂
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import java.io.*; import java.util.*; interface fruit { public abstract void eat(); } class Apple implements fruit { public void eat() { System.out.println("Apple"); } } class Orange implements fruit { public void eat() { System.out.println("Orange"); } } // 操作属性文件类 class init { public static Properties getPro() throws FileNotFoundException, IOException { Properties pro = new Properties(); File f = new File("fruit.properties");//地址写全 if (f.exists()) { pro.load(new FileInputStream(f)); } else { pro.setProperty("apple", "reflectAndGeneric.Apple"); pro.setProperty("orange", "reflectAndGeneric.Orange"); pro.store(new FileOutputStream(f), "FRUIT CLASS"); } return pro; } } class Factory { public static fruit getInstance(String ClassName) { fruit f = null; try { f = (fruit) Class.forName(ClassName).newInstance(); } catch (Exception e) { e.printStackTrace(); } return f; } } // 结合属性文件的反射工厂类。 public class reflectionFactory { public static void main(String[] a) throws FileNotFoundException, IOException { Properties pro = init.getPro(); fruit f = Factory.getInstance(pro.getProperty("apple")); if (f != null) { f.eat(); } } }
输出结果:
Apple
To follow the path:
look to the master,
follow the master,
walk with the master,
see through the master,
become the master.