field To Getter method - Java Reflection

Java examples for Reflection:Field Get

Description

field To Getter method

Demo Code


//package com.java2s;
import java.beans.IntrospectionException;

import java.beans.PropertyDescriptor;

public class Main {
    public static void main(String[] argv) throws Exception {
        Class clazz = String.class;
        String fieldName = "java2s.com";
        System.out.println(fieldToGetter(clazz, fieldName));
    }//from   www  . j ava  2 s .  co  m

    public static <T> String fieldToGetter(Class<T> clazz, String fieldName) {
        try {
            PropertyDescriptor propertyDescriptor = new PropertyDescriptor(
                    fieldName, clazz);
            return propertyDescriptor.getReadMethod().getName();
        } catch (IntrospectionException e) {
            e.printStackTrace();
            return null;
        }
        // return "get" + fieldName.substring(0, 1).toUpperCase() +
        // fieldName.substring(1);
    }
}

Related Tutorials