使用Java反射,您可以檢查類的方法并在運行時調(diào)用它們。 這可以用來檢測給定的類有哪些getter和setter。 你不能明確地要求getter和setter,所以你將不得不掃描一個類的所有方法,并檢查每個方法是否是getter或setter。
首先讓我們建立一個 getters and setters的規(guī)則:
- get getter方法的名字以“get”開始,取0個參數(shù),并返回一個值。
- set setter方法的名字以“set”開始,并且取1個參數(shù)。
安裝者可能會也可能不會返回一個值。 一些setter返回void,一些set的值,另外一些setter被調(diào)用的對象用于方法鏈接。 因此你不應(yīng)該假設(shè)一個setter的返回類型。
這是一個代碼示例,可以找到一個類的getter和setter:
public static void printGettersSetters(Class aClass){
Method[] methods = aClass.getMethods();
for(Method method : methods){
if(isGetter(method)) System.out.println("getter: " + method);
if(isSetter(method)) System.out.println("setter: " + method);
}
}
public static boolean isGetter(Method method){
if(!method.getName().startsWith("get")) return false;
//get方法肯定沒有參數(shù)
if(method.getParameterTypes().length != 0) return false;
if(void.class.equals(method.getReturnType()) return false;
return true;
}
public static boolean isSetter(Method method){
if(!method.getName().startsWith("set")) return false;
//set可以在參數(shù)上做文章。參數(shù)肯定是1
if(method.getParameterTypes().length != 1) return false;
return true;
}
實戰(zhàn)
package com.reflection.detail;
import java.lang.reflect.Method;
/**
* Created by Fant.J.
* 2018/2/7 15:20
*/
public class Reflection_GetterSetter {
public static void printGettersSetters(Class aClass) {
Method[] methods = aClass.getMethods();
for (Method method : methods) {
if (isGetter(method)) {
System.out.println("getter: " + method);
}
if (isSetter(method)) {
System.out.println("setter: " + method);
}
}
}
/**
* 是否是getter
*
* @param method method對象
* @return 布爾值
*/
public static boolean isGetter(Method method) {
//get開頭
if (!method.getName().startsWith("get")) {
return false;
}
//參數(shù)長度不是0
if (method.getParameterTypes().length != 0) {
return false;
}
//返回值不為空
if (void.class.equals(method.getReturnType())) {
return false;
}
return true;
}
/**
* 是否是setter
*
* @param method
* @return
*/
public static boolean isSetter(Method method) {
//是否是set開頭
if (!method.getName().startsWith("set")) {
return false;
}
//是否參數(shù)長度等于1
if (method.getParameterTypes().length != 1) {
return false;
}
return true;
}
public static void main(String[] args) {
Class aClass = People.class;
printGettersSetters(aClass);
}
}
getter: public java.lang.String com.reflection.detail.People.getName()
getter: public java.lang.Integer com.reflection.detail.People.getId()
setter: public void com.reflection.detail.People.setName(java.lang.String)
setter: public void com.reflection.detail.People.setId(java.lang.Integer)
getter: public final native java.lang.Class java.lang.Object.getClass()
項目代碼:github鏈接