标签:构造方法 ati inf object item const 属性 throws tco
public class TestClass { public String classInfo; public String getClassInfo() { return classInfo; } public TestClass(String classInfo) { this.classInfo = classInfo; System.out.println("invoke this param classInfo constructor."); } public TestClass() { System.out.println("invoke this default constructor."); } public void setClassInfo(String classInfo) { this.classInfo = classInfo; } static { System.out.println("init first class."); } public void showinfo() { System.out.println("this is default show info method."); } public void showinfo(String info) { System.out.println("this is have param method."); System.out.println("param context:"+info); } }
import org.junit.Test; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; public class getClassInfoTest { @Test public void testDemo() throws Exception { /** * 1.实现反射的第一步:获取对象的类型信息,java中指存放类型信息的.class文件 * 2.在这里是获取对象的所有构造方法. * 3.找到需要的构造方法. * 4.调用指定构造方法,创建对象. */ Class clazz=Class.forName("TestClass"); /** * 获取构造方法 * 调用newInstance(...) 相当于 new TestClass(...) */ Constructor[] constructors=clazz.getConstructors(); System.out.println("constructor item:"+‘\n‘); arrayToStringItem(constructors); Object test=constructors[0].newInstance(); Object test2=constructors[1].newInstance("hello"); /** * 获取属性 */ Field[] fields=clazz.getFields(); System.out.println("field item:"+‘\n‘); arrayToStringItem(fields); Field field=fields[0]; System.out.println("field name:"+field.getName()); System.out.println("get dafault constructor field value:"+field.get(test)); System.out.println("get have param constructor field value:"+field.get(test2)); /** * 获取方法 */ Method[] methods=clazz.getMethods(); System.out.println("method item:"+‘\n‘); arrayToStringItem(methods); System.out.println("invoke "+methods[0].getName()+" get return value:"+methods[0].invoke(test2)); } public void arrayToStringItem(Object[] args) { for (Object c:args) { System.out.println(c); } } }
标签:构造方法 ati inf object item const 属性 throws tco
原文地址:https://www.cnblogs.com/laxilo/p/9534477.html