获取class的方法: Class<?> clazz = Class.forName("完整类名") //最常用 Class<?> clazz = 对象.getClass() Class<?> clazz = 类.Class 常用api: 获取属性:clazz.getDeclaredFields() 获取方法:clazz.getDeclaredMethods() 获取某一方法: Method method = clazz.getDeclaredMethod(方法名, new Class[]{String.class, String.class}//参数类型Class列表) 方法调用:method.invoke(对象实例,{参数}) 获取构造:clazz.getDeclaredConstructor() public class Main { public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException { User user = new User(); Class<?> clazz = Class.forName("com.example.demo.reflect.User"); //加载class Field[] fields = clazz.getDeclaredFields(); //获取属性 for (Field field : fields) { System.out.println("属性名:"+field.getName()+",属性类型:"+field.getType().getSimpleName()); } Field nameField = clazz.getDeclaredField("name"); nameField.setAccessible(true); //设置私有的属性也可以访问 nameField.set(user, "abc"); System.out.println("user.name = " + user.getName()); Method[] methods = clazz.getDeclaredMethods(); //获取方法 for (Method method : methods) { System.out.println(method.getName()); //获取方法名 Class<?>[] parameterTypes = method.getParameterTypes(); //获取方法参数类型 for (Class<?> parame : parameterTypes) { System.out.println(parame.getSimpleName()); //获取方法参数类型名 } } Method play = clazz.getDeclaredMethod("play", new Class[]{String.class, String.class}); //获取play方法,传入其参数类型 play.setAccessible(true); Object invoke = play.invoke(user, new Object[]{"a", "b"}); //调用user的play方法,传入参数 String clazzName = clazz.getName(); int modifiers = clazz.getModifiers(); TypeVariable<? extends Class<?>>[] typeParameters = clazz.getTypeParameters(); String simpleName = clazz.getSimpleName(); System.out.println(clazzName+" "+modifiers+" "+simpleName); Constructor<?> constructor1 = clazz.getDeclaredConstructor(); //获取无参构造 Object o1 = constructor1.newInstance(); System.out.println(o1); Constructor<?> constructor2 = clazz.getDeclaredConstructor(new Class[]{String.class, int.class}); //获取有参构造 User o2 = (User)constructor2.newInstance(new Object[]{"xiao a", 15}); //传入有参构造的参数 System.out.println(o2.getName()); Object o = clazz.newInstance(); System.out.println(o); } }
JAVA反射
于 2023-10-09 16:51:17 首次发布