invoke Get Method on java Bean - Java Reflection

Java examples for Reflection:Java Bean

Description

invoke Get Method on java Bean

Demo Code


//package com.java2s;

import java.lang.reflect.Method;

public class Main {
    public static void main(String[] argv) throws Exception {
        Object o = "java2s.com";
        String fieldName = "java2s.com";
        System.out.println(invokeGet(o, fieldName));
    }/*from  w w  w . j  a v a  2 s  . co  m*/

    public static Object invokeGet(Object o, String fieldName) {
        Method method = getGetMethod(o.getClass(), fieldName);
        try {
            return method.invoke(o, new Object[0]);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static Method getGetMethod(Class objectClass, String fieldName) {
        StringBuffer sb = new StringBuffer();
        sb.append("get");
        sb.append(fieldName.substring(0, 1).toUpperCase());
        sb.append(fieldName.substring(1));
        try {
            return objectClass.getMethod(sb.toString());
        } catch (Exception e) {
        }
        return null;
    }
}

Related Tutorials