码迷,mamicode.com
首页 > 其他好文 > 详细

泛型擦除 反射 自动装配

时间:2014-12-29 22:42:05      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:

1.泛型擦除

package cn.itcast.demo;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class Demo1 {

    public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
        // 定义一个List<Integer>
        List<Integer> list = new ArrayList<Integer>();

        // 添加一个字符串 "abc"
        // list.add("abc");

        // 解决问题,使用反射
        // 1.得到List的Class。
        Class clazz = list.getClass();
        
        //2.通过clazz去获取add方法.
        Method addMethod=clazz.getMethod("add", Object.class);
        
        //3.调用add方法,将"abc"添加.
        
        addMethod.invoke(list, "abc");
        
        System.out.println(list);
    }
}

2.四种获取对象的方式.
1.new
2.反射
3.IO流(Object流) ----注意需要实现Serializable
4.clone() ---需要在类中重写clone()方法实现Cloneable接口.

package cn.itcast.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.junit.Test;

//获取对象
public class Demo2 {

    // 1.new
    @Test
    public void fun1() {
        Person p = new Person();
    }

    // 使用反射
    @Test
    public void fun2() throws ClassNotFoundException, InstantiationException,
            IllegalAccessException {
        Class c = Class.forName("cn.itcast.demo.Person");
        c.newInstance();
    }

    // 3.使用IO流.
    @Test
    public void fun3() throws FileNotFoundException, IOException {
        // 将一个对象写入到object.txt文件中.
        Person p = new Person();
        p.setName("tom");
        p.setSex("male");
        p.setAddress("北京");

        // 在java中如果描述路径要使用 两个\\,也可以使用一个/。

        File file = new File("D:/java0106/workspace/day02/src/object.txt");
        // // 绝对路径
        // 相对路径
        // File file=new File("src/object.txt");

        // 在开发中获取classpath路径。 获取我们的classpath路径的根目录. 那么如果文件存在于bin中,就可以直接在后面写路径
        // String path = Demo2.class.getResource("/object.txt").getPath();

        // File file=new File(path);

        // System.out.println(file.exists());

        writeObjectToFile(p, file);

    }

    @Test
    public void fun4() throws FileNotFoundException, IOException,
            ClassNotFoundException {
        File file = new File("D:/java0106/workspace/day02/src/object.txt");
        Person p = (Person) readObjectFromFile(file);

        System.out.println(p);
    }

    // 从文件中读取对象
    private Object readObjectFromFile(File file) throws FileNotFoundException,
            IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
        Object obj = ois.readObject();
        ois.close();
        return obj;
    }

    // 将对象写入到文件中的操作
    private void writeObjectToFile(Object obj, File file)
            throws FileNotFoundException, IOException {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
                file));

        oos.writeObject(obj);
        oos.flush();
        oos.close();

    }

    // 使用克隆
    @Test
    public void fun5() throws CloneNotSupportedException {
        Person p = new Person();
        p.setName("tom");
        p.setSex("male");
        p.setAddress("北京");
        
        
        Person pp = (Person) p.clone(); // 得到一个p对象的副本
        
        System.out.println(pp);
    }
}

2

package cn.itcast.demo;

import java.io.Serializable;

public class Person implements Cloneable{// implements Serializable {

    // private static final long serialVersionUID = 1L;
    private String name;
    private String sex;
    private String address;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", sex=" + sex + ", address=" + address
                + "]";
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

}

3.自动装配操作.
创建一个Map集合.
map.put("name","tom");
map.put("sex","男");
map.put("address","北京");

Person类.
class Person{

private String name;
private String sex;
private String address;

get/set方法.
}

要求,使用反射,将map集合中key值与Person类中属性名相同的用key的value对Person类的属性赋值.

不使用Field类,使用 Method类操作.

package cn.itcast.demo;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.junit.Test;

public class Demo3 {

    public static void main(String[] args) throws SecurityException,
            NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
        Map<String, String> map = new HashMap<String, String>();
        map.put("name", "tom");
        map.put("sex", "男");
        map.put("address", "北京");

        Person p = new Person();

        // 1.得到集合中的所有key
        Set<String> keys = map.keySet();

        // 2.得到所有的Person类中的属性.
        Class clazz = p.getClass();
        Field[] fields = clazz.getDeclaredFields();// 属性是private

        // 3.遍历属性,判断keys是否包含这些属性.

        for (Field field : fields) {
            // 得到属性名称.
            String fieldName = field.getName();

            if (keys.contains(fieldName)) {
                // map集合的key中包含这样的属性名。那么就需要调用这个属性对应的set方法将key对应的value进行赋值操作.

                // 1.得到value
                String value = map.get(fieldName);

                // 2.得到属性对应的set方法
                Method setMethod = clazz.getMethod(getSetMethodName(fieldName),
                        String.class);
                
                //3.调用方法进行赋值.
                
                setMethod.invoke(p, value);

            }
        }
        
        System.out.println(p);
    }

    public static String getSetMethodName(String param) {

        return "set" + (char) (param.charAt(0) - 32) + param.substring(1);

    }

    @Test
    public void fun() {
        // ‘n‘---->N

        System.out.println((char) (‘n‘ - 32));

    }
}

 

泛型擦除 反射 自动装配

标签:

原文地址:http://www.cnblogs.com/spadd/p/4192444.html

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