Java反射的基本操作

xiaoxiao2021-02-28  108

最近重新复习了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");

测试结果:

获取类的属性

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());

获取类的方法:

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");

调用类的方法:

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(); }
转载请注明原文地址: https://www.6miu.com/read-83400.html

最新回复(0)