1. 程式人生 > >Use reflector to access and modify private parameter

Use reflector to access and modify private parameter

Just one important setting: fields[i].setAccessible(true);
關注微信公眾號:
huyouxiao.com
回覆語言名稱,比如java,python,go,C, C++.有海量資源免費贈送!

package com.kado;

import java.lang.reflect.Field;

public class ReflectionUtils {
    public static Object getInstance(Class clazz, String ... args) {
        try {
            Object object = Class.forName(clazz.getName()).newInstance();
            Field[] fields = clazz.getDeclaredFields();
            for(int i=0; i<fields.length; i++) {
                fields[i].setAccessible(true);
                for(int j=0; j<args.length; j++) {
                    String nameAndValue = args[j];
                    String nameAndValuePair[] = nameAndValue.split(":");
                    if(fields[i].getName().equals(nameAndValuePair[0])) {
                        fields[i].set(object, nameAndValuePair[1]);
                        break;
                    }
                }
            }
            return object;
        } catch(ClassNotFoundException|InstantiationException|IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void main(String args[]) {
        Object object = getInstance(User.class, "username:kado","password:123456");
        User user = (User) object;
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
    }
}

related User bean code:

package com.kado;

public class User {
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }
    public User(){}
}

more, if the bean do not have getter and setter method for its private attributes. you can use:

  1. fields[i].set(object, nameAndValuePair[1]); to set value.
  2. Object before=fields[i].get(user); to get value.
    example code:
package com.kado;

import java.lang.reflect.Field;

public class Main {

    public static void main(String[] args) throws IllegalAccessException {
	    User user = new User("kado", "123456");

	    Field[] fields = user.getClass().getDeclaredFields();
	    for(int i=0; i<fields.length; i++)
        {
            fields[i].setAccessible(true);
            Object before=fields[i].get(user);
            System.out.println("before modify:"+before);

            if(fields[i].getName().equals("username")) {

                fields[i].set(user, "Kevin");
            } else if(fields[i].getName().equals("password")) {
                fields[i].set(user, "654321");
            }
            Object after=fields[i].get(user);
            System.out.println("after modify:"+after);
        }
    }
}

I have reference yaerfeng java高階程式設計-使用反射強制給private欄位賦值 , Thank you!