集册 Java实例教程 用设置器设置字段值

用设置器设置字段值

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

520
用设置器设置字段值


//package com.nowjava;
/** 
来 自 
nowjava.com - 时代Java
**/


import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;


public class Main {

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

        Object obj = "nowjava.com";

        String fieldName = "nowjava.com";

        Object value = "nowjava.com";

        setFieldValueWithSetter(obj, fieldName, value);

    }


    public static void setFieldValueWithSetter(Object obj,

            String fieldName, Object value) throws NoSuchMethodException,

            InvocationTargetException, IllegalAccessException {/**来自 N o w  J a v a  .   c o m**/

        Method method = getSetterMethodForField(obj,

                getSetterMethodNameForField(fieldName), value.getClass());

        method.invoke(obj, value);

    }


    public static Method getSetterMethodForField(Object obj,

            String fieldName, Class type) throws NoSuchMethodException {

        return obj.getClass().getDeclaredMethod(fieldName, type);

    }


   
展开阅读全文