Java - Write code to get String Property from an Object using Reflection

Requirements

Write code to get String Property from an Object using Reflection

Demo

//package com.book2s;
import java.lang.reflect.InvocationTargetException;

public class Main {
    public static void main(String[] argv) {
        Object bean = "book2s.com";
        String name = "toString";
        System.out.println(getStringtProperty(bean, name));
    }//w  ww  .ja  v a  2 s  . co  m

    public static String getStringtProperty(Object bean, String name) {
        String methodName1 = "is" + Character.toUpperCase(name.charAt(0))
                + name.substring(1);
        String methodName2 = "get" + Character.toUpperCase(name.charAt(0))
                + name.substring(1);

        Class<?> clazz = bean.getClass();
        try {
            return (String) clazz.getMethod(methodName1).invoke(bean);
        } catch (IllegalAccessException | IllegalArgumentException
                | InvocationTargetException | NoSuchMethodException
                | SecurityException e) {
            try {
                Object ret = clazz.getMethod(methodName2).invoke(bean);
                return (ret instanceof String) ? (String) ret : null;
            } catch (IllegalAccessException | IllegalArgumentException
                    | InvocationTargetException | NoSuchMethodException
                    | SecurityException ex) {
                return null;
            }
        }
    }
}