java反射笔记

it2023-09-18  73

java反射 通过反射的方式调用,分为3个步骤

package com.example.mydemo; class Person { private static String mName; public static void setName(String name) { mName = name; } public static String getName() { return mName; } }

通过反射调用静态类的步骤: 1)通过Class.forName,参数是包含包名的类,比如"com.example.mydemo.Person",获取Class对象,比如person 2)调用getMethod方法获取Method对象 参数1是方法名称,比如setName 参数2是参数类型,比如String.class 3)调用Method对象的invoke方法,参数1是Class对象,比如person,参数2是方法的传值比如“sunny”。

示例代码如下: try { Class<?> person = Class.forName(“com.example.mydemo.Person”); Method method = person.getMethod(“setName”, String.class); method.invoke(person, “sunny”); Method getNameMethod = person.getMethod(“getName”); String personNameStr = (String)getNameMethod.invoke(person); Log.d(“testtest”, “personNameStr:”+personNameStr);

} catch (Exception e) { e.printStackTrace(); }

最新回复(0)