Java反射的基本操作 野性酷女 2022-06-16 05:56 163阅读 0赞 最近重新复习了Java反射,记录如下。 通过反射获取类的基本信息: 获取类的构造函数: public static void getConstructors(Object obj) { Class class1 = obj.getClass(); //get class1's constructors Constructor[] constructors = class1.getDeclaredConstructors(); for (Constructor constructor : constructors) { String cName = constructor.getName(); System.out.print(cName+"("); Class[] parameterTypes = constructor.getParameterTypes(); for (Class type : parameterTypes) { System.out.print(type.getName()+","); } System.out.println(")"); } } //测试代码: ReflactDemo.getConstructors(new Integer(1)); System.out.println("-----"); ReflactDemo.getConstructors("test"); 测试结果: ![这里写图片描述][SouthEast] 获取类的属性 public static void getFields(Object obj) { Class class1 = obj.getClass(); //get class1's members Field[] fields = class1.getDeclaredFields(); for (Field field : fields) { String fieldName = field.getName(); String fieldType = field.getType().getSimpleName(); System.out.println(fieldType + " " + fieldName); } } //测试代码 class TestClass1{ public String name = "bear"; public int age = 18; public float power = (float) 10.6; public TestClass1() { this.name = "bear2"; } public void print() { System.out.println(name+" "+age+" "+power); } } ReflactDemo.getFields(new TestClass1()); ![这里写图片描述][SouthEast 1] 获取类的方法: public static void getMethods(Object object) { Class class1 = object.getClass(); //get class1's methods; Method[] methods = class1.getDeclaredMethods(); for (Method method : methods) { Type returnType = method.getGenericReturnType(); System.out.print(returnType+" "); System.out.print(method.getName()+"("); Class[] types = method.getParameterTypes(); for (Class type : types) { System.out.print(type.getName()+","); } System.out.println(")"); } } //测试代码: ReflactDemo.getMethods("klajs"); ![这里写图片描述][SouthEast 2] 调用类的方法: try { Class class1 = Class.forName("com.bear.TestClass1"); Method method = class1.getMethod("print", new Class[]{}); method.invoke(class1.newInstance()); } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException e) { e.printStackTrace(); } [SouthEast]: /images/20220616/8b6006c3f5d240768c13bb2046bd872d.png [SouthEast 1]: /images/20220616/4aeabd6108ef495b8102c3c6b036eefe.png [SouthEast 2]: /images/20220616/be2d68596712421f9dbe1e6c5bb24b25.png
还没有评论,来说两句吧...