非深入探寻Java反射机制 (Getters and Setters)

首先定义setter方法和getter方法:

  • getter方法:

        getter方法的方法名以get开头,没有参数,有返回值


  • setter方法:

        setter方法的方法名以set开头,有一个参数,返回值可有可无



现在,我们拿来写一个程序判断某个类中的每一个方法是不是getter/setter方法

	public static void printGettersSetters(String className) throws ClassNotFoundException {
		Class theClass = Class.forName(className);
		Method[] methods = theClass.getMethods();
		
		for (Method m : methods) {
			if (isGetter(m))
				System.out.println("Getter: [ " + m + " ]");
			if (isSetter(m))
				System.out.println("Setter: [ " + m + " ]");
		}
	}
	
	public static boolean isGetter(Method method) {
		if (!method.getName().startsWith("get"))
			return false;
		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;
		if (method.getParameterTypes().length != 1)
			return false;
		
		return true;
	}







你可能感兴趣的:(java,reflection)