码迷,mamicode.com
首页 > 编程语言 > 详细

Java中反射代码实例

时间:2017-07-27 15:53:15      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:ble   pack   star   函数   try   建立   代码   main   package   

我们建立一个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中反射代码实例

标签:ble   pack   star   函数   try   建立   代码   main   package   

原文地址:http://www.cnblogs.com/legion/p/7244643.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!