1. 程式人生 > >Java中反射代碼實例

Java中反射代碼實例

tcl print void ons [] nbsp sys this per

我們建立一個Person類,對此進行反射操作。

package myReflection;

public class Person {
    private String name;
    private String id;
    Person(){}
    /**
     * @param name
     * @param id
     */
    public Person(String name, String id) {
        super();
        this.name = name;
        this.id = id;
    }
    
/** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the id */ public String getId() { return id; }
/** * @param id the id to set */ public void setId(String id) { this.id = id; } }

分別對constructor‘、屬性和方法反射

test1====無參數構造函數

test2 ====有參數構造函數

test3=====屬性

test4=====方法

package myReflection;

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

import org.junit.Test; public class useReflection { public static void main(String[] args) throws ClassNotFoundException { // TODO Auto-generated method stub Class c1=Person.class; Class c2=new Person().getClass(); Class c3=Class.forName("myReflection.Person"); } @Test public void test4() throws Exception{ Class c=Class.forName("myReflection.Person"); Person p=(Person) c.newInstance(); Method m=c.getDeclaredMethod("setName", String.class); m.invoke(p, "Lannister"); System.out.println(p.getName()); } @Test public void test3() throws Exception{ try { Class c=Class.forName("myReflection.Person"); Person p=(Person) c.newInstance(); Field f1=c.getDeclaredField("name"); f1.setAccessible(true); f1.set(p, "Stark"); System.out.println(f1.get(p)); } catch (Exception e) { // TODO: handle exception } } @Test public void test2() throws Exception { Class c=Class.forName("myReflection.Person"); Constructor cs=c.getConstructor(String.class,String.class); Person p1=(Person)cs.newInstance("Jon","Snow"); System.out.println(p1.getId()+" "+p1.getName()); } @Test public void test1() throws Exception{ Class cl3=Class.forName("myReflection.Person"); Person p =(Person)cl3.newInstance(); p.setName("Tully"); System.out.println(p.getName()); } }

Java中反射代碼實例