反射-getter/setter-java
1 import java.lang.reflect.Method; 2 3 /** 4 * Created with IDEA 5 * author:foreign 6 * Date:2019/9/30 7 * Time:10:40 8 */ 9 public class ReflectionFk { 10 public static void main(String[] args) { 11 Class clazz = PersonFk.class; 12 Method[] methods = clazz.getMethods(); 13 for (Method method : methods) { 14 if (isGetter(method)) { 15 System.out.println("getter方法:" + method); 16 } 17 if (isSetter(method)) { 18 System.out.println("setter方法:" + method); 19 } 20 } 21 } 22 //setter方法不一定有返回值 23 private static boolean isSetter(Method method) { 24 if (!method.getName().startsWith("set")) { 25 return false; 26 } 27 if (method.getParameterTypes().length != 1) { 28 return false; 29 } 30 return true; 31 } 32 33 private static boolean isGetter(Method method) { 34 if (!method.getName().startsWith("get")) { 35 return false; 36 } 37 if (method.getParameterTypes().length != 0) { 38 return false; 39 } 40 if (void.class.equals(method.getReturnType())) { 41 return false; 42 } 43 return true; 44 } 45 }