集册 Java实例教程 在Java Bean上调用Set方法

在Java Bean上调用Set方法

欢马劈雪     最近更新时间:2020-01-02 10:19:05

474
在Java Bean上调用Set方法

/** from 
n o w    j a v a  . c o m**/

//package com.nowjava;

import java.lang.reflect.Field;

import java.lang.reflect.Method;


public class Main {

    public static void main(String[] argv) throws Exception {

        Object o = "nowjava.com";

        String fieldName = "nowjava.com";

        Object value = "nowjava.com";

        invokeSet(o, fieldName, value);

    }


    public static void invokeSet(Object o, String fieldName, Object value) {

        Method method = getSetMethod(o.getClass(), fieldName);

        try {

            method.invoke(o, new Object[] { value });

        } catch (Exception e) {

            e.printStackTrace();

        }//from n o w  j a v a  . c o m

    }


    @SuppressWarnings({ "unchecked", "rawtypes" })

    public static Method getSetMethod(Class objectClass, String fieldName) {

        try {

            Class[] parameterTypes = new Class[1];

            Field field = objectClass.getDeclaredField(fieldName);

            parameterTypes[0] = field.getType();

            StringBuffer sb = new StringBuffer();

            sb.append("set");

            sb.append(fieldName.substring(0, 1).toUpperCase());

            sb.ap
展开阅读全文