set Field Value With Setter - Java Reflection

Java examples for Reflection:Setter

Description

set Field Value With Setter

Demo Code


//package com.java2s;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {
    public static void main(String[] argv) throws Exception {
        Object obj = "java2s.com";
        String fieldName = "java2s.com";
        Object value = "java2s.com";
        setFieldValueWithSetter(obj, fieldName, value);
    }// ww  w.  j av a  2s  .  co m

    public static void setFieldValueWithSetter(Object obj,
            String fieldName, Object value) throws NoSuchMethodException,
            InvocationTargetException, IllegalAccessException {
        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);
    }

    public static String getSetterMethodNameForField(String fieldName) {
        return "set" + fieldName.substring(0, 1).toUpperCase()
                + fieldName.substring(1);
    }
}

Related Tutorials