Jenkov.com
Tutorials Books About
Java Reflection

1 Java Reflection Tutorial
2 Java Reflection - Classes
3 Java Reflection - Constructors
4 Java Reflection - Fields
5 Java Reflection - Methods
6 Java Reflection - Getters and Setters
7 Java Reflection - Private Fields and Methods
8 Java Reflection - Annotations
9 Java Reflection - Generics
10 Java Reflection - Arrays
11 Java Reflection - Dynamic Proxies
12 Java Reflection - Dynamic Class Loading and Reloading




Java Reflection - Getters and Setters


Using Java Reflection you can inspect the methods of classes and invoke them at runtime. This can be used to detect what getters and setters a given class has. You cannot ask for getters and setters explicitly, so you will have to scan through all the methods of a class and check if each method is a getter or setter.

First let's establish the rules that characterizes getters and setters:

Setters may or may not return a value. Some setters return void, some the value set, others the object the setter were called on for use in method chaining. Therefore you should make no assumptions about the return type of a setter.

Here is a code example that finds getter and setters of a class:

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;
  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;
}


Connect with me: Newsletter - Get all my free tips!