快速了解反射的使用

it2024-07-19  38

1.通过反射得到类 Class clazz = A.Class;得到一个A类clazz = class A; A a = new A()a.getClass(); 也是得到一个A类,a.getClass()=class A; Class t = Class.forName(“animal.A”);括号里写类的路径;t = class A; 2.通过反射调用类里的成员变量 Field f = a.getField(“a”);括号里写成员变量名可以得到类A的成员变量 f.set(a,0)对类A的成员变量赋值 f.get(a)得到类A的成员变量a的值 f.getType()可以得到a的数据类型 3.通过反射调用类里的方法 Method method = a.getMethod(“dog”, int.class);得到带参的dog方法Method method = a.getMethod(“dog”);得到不带参的dog方法 method.invoke(a.newInstance())通过实例化对象调用方法

代码案例

public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException, InstantiationException { //getClass()和class的区别 Class clazz = Animals.class; Animals a = new Animals(); System.out.println(clazz+"分别的得到两个类名 "+a.getClass()); System.out.println("得到类的全部名称:"+clazz.getName()); System.out.println("得到类名:"+clazz.getSimpleName()); Field field = clazz.getField("a"); //设置类animal的成员变量的值 field.set(a,0); //得到成员变量的值 System.out.println(field.get(a)); System.out.println(Arrays.toString(clazz.getFields())); System.out.println("返回a的类型:"+field.getType()); // Method method = clazz.getMethod( "animal"); // 获取animal的dog(int a)方法 Method method2 = clazz.getMethod("dog", int.class); // 实例化对象并传入参数 method2.invoke(clazz.newInstance(),6); //动态加载类,获取当前类的对象 Class t = Class.forName("yushiweektwo.Polymorphism.Animals"); //获取animal类的dog()方法 Method method3 = t.getMethod("dog"); //通过实例化的对象,调用无参的方法 method3.invoke(t.newInstance()); Class c = Human.class; } } class Animals { public int a,b; public String i,v; public Animals() { System.out.println("动物在叫"); } public void cat() { System.out.println("小猫在叫"); } public void dog() { System.out.println("狗在吃shit"); } public void dog(int a) { System.out.println("我这是带有形参的狗"); } } interface Human { /** * 吃的意思 */ void eat(); }

输出结果

class yushiweektwo.Polymorphism.Animals分别的得到两个类名 class yushiweektwo.Polymorphism.Animals 得到类的全部名称:yushiweektwo.Polymorphism.Animals 得到类名:Animals 0 [public int yushiweektwo.Polymorphism.Animals.a, public int yushiweektwo.Polymorphism.Animals.b, public java.lang.String yushiweektwo.Polymorphism.Animals.i, public java.lang.String yushiweektwo.Polymorphism.Animals.v] 返回a的类型:int 动物在叫 我这是带有形参的狗 动物在叫 狗在吃shit Process finished with exit code 0```
最新回复(0)