2019独角兽企业重金招聘Python工程师标准>>>
试验:
package reflect;import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;import org.junit.Test;
/*** @author seng* 学习java反射技术 */
public class Demo1 {@Testpublic void test1() {// TODO Auto-generated method stubtry {// 1、加载类的字节码,方式 1Class clazz = Class.forName("reflect.Person");// 2、加载类的字节码,方式 2clazz = new Person().getClass();// 3、加载类的字节码,方式 3clazz = Person.class;// 得到Person 类的所有方法Method [] personMethods = clazz.getMethods();// 得到 Person 类的构造函数Constructor [] cons = clazz.getConstructors();// 得到 Person 类的属性域Field [] field = clazz.getFields();// 调用无参的构造函数实例化Person对象try {Person p = null;p = (Person) clazz.newInstance();//p = (Person) cons[1].newInstance(null);p.showInfo();} catch (InstantiationException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();}} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}@Testpublic void test2(){Class clazz;try {clazz = Class.forName("reflect.Person");Constructor con = clazz.getConstructor(String.class,int.class);Person p = (Person) con.newInstance("zeng guangyao",22);p.showInfo();} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SecurityException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (NoSuchMethodException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InstantiationException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InvocationTargetException e) {// TODO Auto-generated catch blocke.printStackTrace();}}
}