1. 程式人生 > >Java反射的基本應用

Java反射的基本應用

lang ger 類型 system uname color 加載 ner tor

反射機制,程序在運行時加載新的類,使程序更加靈活

public class HelooReflect {
    public static void main(String[] args) {
        // 獲取類
        testClass();
    }
    private static void testClass() {
        // 創建一個學生類的對象
        Student student = new Student();
        try {
            // 開始獲取類
            Class clazz1 = Student.class
; Class clazz2 = student.getClass(); Class clazz3 = Class.forName("com.bjsxt.java.clc.fanshe.Student"); //判斷類對象是否相等 System.out.println(clazz1 == clazz2); System.out.println(clazz1 == clazz3); //常見 方法 System.out.println("類的名字" + clazz1.getName()); System.out.println(
"類的簡稱" + clazz1.getSimpleName()); System.out.println("包的信息" + clazz1.getPackage().getName()); System.out.println("獲取包名" + clazz1.getPackage()); System.out.println("獲取修飾符" + clazz1.getModifiers()); System.out.println("獲取父類" + clazz1.getSuperclass()); System.out.println(
"獲取父類的超類" + clazz1.getGenericSuperclass()); System.out.println("判斷是否為接口" + clazz1.isInterface()); System.out.println("獲取類加載器" + clazz1.getClassLoader()); //基本類型9=(8種基本數據類型的類+1void) System.out.println(int.class == Integer.class);//不等 //判斷是否是基本類型 System.out.println(int.class.isPrimitive()); System.out.println(Integer.class.isPrimitive()); System.out.println("數組是引用類型" + int[].class.isPrimitive()); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

獲取類的名字,方法,屬性,構造器

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Test2 {
    public static void main(String[] args) {
        try {
            Class clazz = Class.forName("bean.User");
            // 獲取類的名字
            clazz.getName();
            /**
             * 獲取屬性信息
             */
            // 只能獲取public的屬性
            Field[] fields1 = clazz.getFields();
            // 可以獲得所有的屬性
            Field[] fields2 = clazz.getDeclaredFields();
            // 輸出獲取到的屬性的個數
            System.out.println(fields1.length);
            System.out.println(fields2.length);
            // 遍歷獲取到的屬性
            for (Field field : fields2) {
                System.out.println("屬性" + field);
            }
            // 獲得屬性的權限
            Field f = clazz.getDeclaredField("uname");
            System.out.println(f);
            /**
             * 獲取方法的信息
             */
            Method[] methods = clazz.getDeclaredMethods();
            Method m01 = clazz.getDeclaredMethod("getUname", null);
            // 如果方法有參,則必須傳遞參數類型對應的class對象
            Method m02 = clazz.getDeclaredMethod("setUname", String.class);
            for (Method method : methods) {
                System.out.println("方法" + method);
            }
            /**
             *獲取構造器信息 
             */
            Constructor[] constructors = clazz.getDeclaredConstructors();
            Constructor c = clazz.getDeclaredConstructor(int.class,int.class,String.class);
            System.out.println("獲得構造器"+c);
            for (Constructor constructor : constructors) {
                System.out.println("構造器"+constructor);
            }
            
            
            
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

通過反射操作類的屬性,方法構造器

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import bean.User;
/**
 * @author clc
 *
 */
public class Test3 {
    public static void main(String[] args) {
        try {
            Class<User> clazz = (Class<User>) Class.forName("bean.User");
            // 通過反射API調用構造方法,構造對象
            // 其實調用了User的無參構造方法
            User u1 = clazz.newInstance();
            System.out.println(u1);
            // 有參調用構造器
            Constructor<User> c = clazz.getDeclaredConstructor(int.class, int.class, String.class);
            User u2 = c.newInstance(1234, 22, "clc");
            System.out.println(u2);
            // 通過反射調用普通方法
            User u3 = clazz.newInstance();
            Method method = clazz.getDeclaredMethod("setUname", String.class);
            // 相當於u3.setUname("clc3");
            method.invoke(u3, "clc3");
            System.out.println(u3);
            // 通過反射操作屬性
            User u4 = clazz.newInstance();
            Field f = clazz.getDeclaredField("uname");
            // 設置屬性不需要安全檢查,可以直接訪問
            f.setAccessible(true);
            // 通過反射直接設置屬性
            f.set(u4, "clc4");
            // 通過反射直接讀取屬性值
            System.out.println(u4.getUname());
            System.out.println(f.get(u4));
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

輔助類User

package bean;
public class User {
    private int id;
    private int age;
    private String uname;
    @Override
    public String toString() {
        return "User [id=" + id + ", age=" + age + ", uname=" + uname + "]";
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + id;
        result = prime * result + ((uname == null) ? 0 : uname.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        User other = (User) obj;
        if (age != other.age)
            return false;
        if (id != other.id)
            return false;
        if (uname == null) {
            if (other.uname != null)
                return false;
        } else if (!uname.equals(other.uname))
            return false;
        return true;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getUname() {
        return uname;
    }
    public void setUname(String uname) {
        this.uname = uname;
    }
    public User(int id, int age, String uname) {
        super();
        this.id = id;
        this.age = age;
        this.uname = uname;
    }
    public User() {
        super();
    }
}

import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import bean.User; /** * @author clc * */ public class Test3 { public static void main(String[] args) { try { Class<User> clazz = (Class<User>) Class.forName("bean.User"); // API調, // 調User User u1 = clazz.newInstance(); System.out.println(u1); // 調 Constructor<User> c = clazz.getDeclaredConstructor(int.class, int.class, String.class); User u2 = c.newInstance(1234, 22, "clc"); System.out.println(u2); // 調 User u3 = clazz.newInstance(); Method method = clazz.getDeclaredMethod("setUname", String.class); // u3.setUname("clc3"); method.invoke(u3, "clc3"); System.out.println(u3); // User u4 = clazz.newInstance(); Field f = clazz.getDeclaredField("uname"); // , f.setAccessible(true); // f.set(u4, "clc4"); // System.out.println(u4.getUname()); System.out.println(f.get(u4)); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

Java反射的基本應用