JAVA 反射(Reflection)

Java反射的例子,从网上找了部分资料,自己改编了一下..

 

 

被测试类

 

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.corejava.common; /** * * @author Prince.Zhang */ public class Employee { private String name; private int age; public String employeeName="Prince"; public static String employee="love"; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return "loveeee"; } public void setName(String name) { this.name = name; } public void printName() { System.out.println("Employee Name:Prince"); } public void printAge(int age) { System.out.println("Employee Age:" + age); } }

 

反射类(含主函数)

 

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.corejava.reflection; import java.lang.reflect.Field; import java.lang.reflect.Method; import com.corejava.common.Employee; import java.lang.Class; import java.lang.reflect.Constructor; /** * * @author Prince.Zhang */ public class ReflectionSample { //得到对象属性 public Object getProperty(Object owner, String fieldName) throws Exception { Class ownerClass = owner.getClass(); // Field field = ownerClass.getField(fieldName); Field field = ownerClass.getDeclaredField(fieldName); field.setAccessible(true); return field.get(owner); } //得到对象的静态属性 public Object getStaticProperty(String className, String fieldName) throws Exception { Class ownerClass = Class.forName(className); Field field = ownerClass.getField(fieldName); return field.get(ownerClass); } //执行对象的方法 public Object invokeMethod(Object owner, String methodName, Object[] args) throws Exception { Class ownerClass = owner.getClass(); Class[] argsClass = new Class[args.length]; for (int i = 0; i < args.length; i++) { argsClass[i] = args[i].getClass(); } Method method = ownerClass.getMethod(methodName, argsClass); return method.invoke(owner, args); } //新建实例 public Object newInstance(String className, Object[] args) throws Exception { Class ownerClass = Class.forName(className); Class[] argClass = new Class[args.length]; for (int i = 0; i < args.length; i++) { argClass[i] = args[i].getClass(); } Constructor cons = ownerClass.getConstructor(argClass); return cons.newInstance(args); } public static void main(String[] args) { Employee employee = new Employee(); String[] classes = new String[0]; // classes[0]="prince"; // classes[1]=employee.getClass(); ReflectionSample rs = new ReflectionSample(); try { System.out.println("getProperty: " + rs.getProperty((Object) employee, "name")); System.out.println("getStaticProperty: " + rs.getStaticProperty("com.corejava.common.Employee", "employee")); System.out.println("invokeMethod: " + rs.invokeMethod(employee, "getName", classes)); Employee e=(Employee)rs.newInstance("com.corejava.common.Employee", classes); e.printName(); } catch (Exception ex) { ex.printStackTrace(); } } }

你可能感兴趣的:(java,string,exception,object,class,templates)