调用指定属性
package reflect; import java.lang.reflect.Field; import java.lang.reflect.Modifier; public class TestFiled { public static void main(String[] args) throws Exception { TestFiled t = new TestFiled(); t.test3(); } //调用运行时类中的指定的属性 public void test3() throws Exception { Class clazz = Person.class; //1.获取指定的属性 //getField(String fieldName):获取运行时类中声明为public的指定属性名为name的属性 Field name = clazz.getField("name"); //2.创建运行时类的对象 Person p =(Person) clazz.newInstance(); System.out.println(p); //3.将运行时类的指定的属性赋值 name.set(p, "巫妖果子"); System.out.println(p); System.out.println(); //getDeclaredField(String fieldName):获取运行时类中声明为private的指定属性名为age Field age = clazz.getDeclaredField("age"); //设置此声明private属性可被操作 age.setAccessible(true); age.set(p, 20); System.out.println(p); } }
调用指定方法
package reflect; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; public class TestMethod { public static void main(String[] args) throws Exception { TestMethod t = new TestMethod(); t.test2(); } //调用运行时类的指定方法 public void test2() throws Exception { Class clazz = Person.class; //getMethod(String methodName,class...params):获取运行时类中声明为public的指定方法 Method m = clazz.getMethod("show"); //实例化运行时类clazz的对象 Person p = (Person)clazz.newInstance(); //调用方法 Object returnValue = m.invoke(p); //打印返回类型 System.out.println(returnValue); Method m1 = clazz.getMethod("toString"); Object returnValue1 = m1.invoke(p); System.out.println(returnValue1); //静态方法的调用 Method m3 = clazz.getMethod("info"); //类名.调用 m3.invoke(Person.class); //getDeclaredMethod(String methodName,Class..params):获取运行时类声明的方法 Method m4 = clazz.getDeclaredMethod("display",String.class,Integer.class); m4.setAccessible(true); Object retuenValue2 = m4.invoke(p, "Chinese",10); System.out.println(retuenValue2); } }
调用构造器
package reflect; import java.lang.reflect.Constructor; public class TestConstructor { public static void main(String[] args) throws Exception { TestConstructor T = new TestConstructor(); T.test2(); } //调用指定的构造器 public void test2() throws Exception { String className = "reflect.Person"; Class clazz = Class.forName(className); Constructor cons = clazz.getDeclaredConstructor(String.class,int.class); cons.setAccessible(true); Person p = (Person)cons.newInstance("巫妖果子",20); System.out.println(p); } }
原文地址:https://www.cnblogs.com/zjm1999/p/10344466.html
时间: 2024-11-05 18:41:22