AdSense

網頁

2018/8/17

Java Reflection(反射)簡單範例

Java Reflection簡單範例如下。


用來測試的POJO User.java

User.java

package idv.matt.model;

public class User {

  private int userId;
  private String userName;
  private int age;

  public User() {

  }

  public User(int userId, String userName, int age) {
    this.userId = userId;
    this.userName = userName;
    this.age = age;
  }

  public int getUserId() {
    return userId;
  }

  public void setUserId(int userId) {
    this.userId = userId;
  }

  public String getUserName() {
    return userName;
  }

  public void setUserName(String userName) {
    this.userName = userName;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

}

測試Java reflection。

ReflectionTest.java

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

import idv.matt.model.User;

public class ReflectionTest {
  
  public static void main(String[] args) {
    
    // 取得Class物件方法1
    Class<?> clazz = User.class;
    
    // 取得Class物件方法2
    clazz = new User().getClass();
    
    // 取得Class物件方法3
    try {
      clazz = Class.forName("idv.matt.model.User");
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
    
    // 類別名稱(含package名稱)
    System.out.println("class coanonical name : " + clazz.getCanonicalName()); 
    
    // 類別名稱
    System.out.println("class simple name : " + (clazz.getSimpleName()));
    
    // package名稱
    System.out.println("class package : " + clazz.getPackage().getName());
    
    // modifier名稱
    System.out.println("class modifiers : " + Modifier.toString(clazz.getModifiers()));
    
    // 建構式名稱
    Constructor<?>[] constructors = clazz.getConstructors();
    for(int i = 0 ; i < constructors.length ; i++) {
      System.out.println("constructors" + i + " : " + constructors[i].getName());
    }
    
    // 屬性/成員變數名稱
    Field[] fields = clazz.getDeclaredFields();
    for(int i = 0 ; i < fields.length ; i++) {
      System.out.println("field" + i + " : " + fields[i].getName());
    }
    
    // 方法名稱
    Method[] methods = clazz.getDeclaredMethods();
    for(int i = 0 ; i < methods.length ; i++) {
      System.out.println("method" + i + " : " + methods[i].getName());
    }
  }
}

印出結果

class coanonical name : idv.matt.model.User
class simple name : User
class package : idv.matt.model
class modifiers : public
constructors0 : idv.matt.model.User
constructors1 : idv.matt.model.User
field0 : userId
field1 : userName
field2 : age
method0 : getUserId
method1 : setUserId
method2 : getUserName
method3 : setUserName
method4 : getAge
method5 : setAge

沒有留言:

AdSense