1. 程式人生 > >通過Java反射機制獲取物件、方法和成員變數

通過Java反射機制獲取物件、方法和成員變數

先定義一個JavaBean

package com.jim.test.Test;

public class User {
    private int id;
    private String name = "abc";
    private String password = "12345";

    public int getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return
name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } private void privateMethod() { System.out.println("access the private method"
); } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", password='" + password + '\'' + '}'; } }
  1. 通過類名生成物件
@Test
    public void testCreateObjectByClassName() throws
ClassNotFoundException, InstantiationException, IllegalAccessException { Class<?> clazz = Class.forName("com.jim.test.Test.User"); User user = (User) clazz.newInstance(); System.out.println(user); }
  1. 訪問私有方法
@Test
    public void testAccessPrivateMethod() throws Exception {
        Class<?> clazz = Class.forName("com.jim.test.Test.User");

        Method method = clazz.getDeclaredMethod("privateMethod", null);
        method.setAccessible(true);
        method.invoke(clazz.newInstance(), null);
    }