get Field Name by getter name - Android java.lang.reflect

Android examples for java.lang.reflect:Field Name

Description

get Field Name by getter name

Demo Code


//package com.java2s;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class Main {
    static String getFieldName(Method method) {

        if (!isGetter(method) && !isSetter(method)) {
            return null;
        }//from www . jav  a  2s . c  o m

        char[] name = method.getName()
                .substring(3, method.getName().length()).toCharArray();
        name[0] = Character.toLowerCase(name[0]);
        return new String(name);
    }

    static boolean isGetter(Method method) {
        return !(method == null || "getId".equals(method.getName())
                || "isTransient".equals(method.getName()) || "isPersistent"
                    .equals(method.getName()))
                && (isBooleanGetter(method) || method.getName().startsWith(
                        "get")
                        && method.getName().length() > 3
                        && method.getReturnType() != Void.class
                        && method.getParameterTypes().length == 0
                        && !Modifier.isStatic(method.getModifiers())
                        && Modifier.isPublic(method.getModifiers()));

    }

    static boolean isSetter(Method method) {
        return method != null && method.getName().startsWith("set")
                && method.getName().length() > 3
                && method.getReturnType() == void.class
                && method.getParameterTypes().length == 1
                && !Modifier.isStatic(method.getModifiers())
                && Modifier.isPublic(method.getModifiers());
    }

    static boolean isBooleanGetter(Method method) {
        return method != null
                && method.getName().startsWith("is")
                && method.getName().length() > 2
                && (method.getReturnType() == boolean.class || method
                        .getReturnType() == Boolean.class);
    }
}

Related Tutorials