java基础-反射

1、反射概述:
JAVA反射是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。
2、总结:反射就是把java类中的各种成分映射成相关的java类。
3、获得字节码方式:
(1)、类名.class 例如:System.in
(2)、对象.getClass() 例如:new Date().getclass
(3)、class.forName(“类名”) 例如:Class.forName(“java.util.Date”)

package demo;

import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;

public class ReflectDemo {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        String str="abc";
        Class cls1=str.getClass();
        Class cls2=String.class;
        Class cls3=Class.forName("java.lang.String");
        System.out.println(cls1==cls2);
        System.out.println(cls1==cls3);

        System.out.println(cls1.isPrimitive());
        System.out.println(int.class.isPrimitive());
        System.out.println(int.class==Integer.class);
        System.out.println(int.class==Integer.TYPE);

        System.out.println(int[].class.isPrimitive());
        System.out.println(int[].class.isArray());

        //反射:获取构造函数
        Constructor constuctor1=String.class.getConstructor(StringBuffer.class);
        String str2=(String)constuctor1.newInstance(new StringBuffer("abc"));
        System.out.println(str2.charAt(2));
        //反射:获取成员变量Field
        ReflectPoint pt1=new ReflectPoint(3, 5);
        Field fieldY=pt1.getClass().getField("y");//获取共有成员变量
        //filedY值不等于5,不是对象的变量,是filed类上的变量
        System.out.println(fieldY.get(pt1));
        Field fieldX=pt1.getClass().getDeclaredField("x");//获取私有成员变量
        fieldX.setAccessible(true);
        System.out.println(fieldX.get(pt1));

        changeStringValue(pt1);
        System.out.println(pt1);

        //反射。获取方法Method
        Method methodCharAt =str.getClass().getMethod("charAt", int.class);
        System.out.println(methodCharAt.invoke(str, 1));
        System.out.println(methodCharAt.invoke(str, new Object[]{2}));

        String startingClassName=args[0];
        Method methodMain=Class.forName(startingClassName).getMethod("main", String[].class);
        //System.out.println(methodMain.invoke(null, new Object[]{new String[]{"123","456","888"}}));
        System.out.println(methodMain.invoke(null, (Object)new String[]{"123","456","888"}));

        //数组的反射关系
        int [] a1=new int[]{1,2,3};
        int [] a2=new int[4];
        int[][] a3=new int[2][3];
        String[] a4=new String[]{"a","b","c"};
        System.out.println(a1.getClass()==a2.getClass());
        //System.out.println(a1.getClass()==a3.getClass());
        //System.out.println(a1.getClass()==a4.getClass());
        System.out.println(a1.getClass().getName());
        System.out.println(a4.getClass().getSuperclass().getName());

        System.out.println(a1);
        System.out.println(a4);
        System.out.println(Arrays.asList(a1));
        System.out.println(Arrays.asList(a4));

        printObject("xyz");
        printObject(a4);
    }
    private static void printObject(Object obj){
        Class clazz=obj.getClass();
        if (clazz.isArray()) {
            int len=Array.getLength(obj);
            for (int i = 0; i < len; i++) {
                System.err.println(Array.get(obj, i));
            }
        } else {
            System.out.println(obj);
        }
    }

    private static void changeStringValue(Object obj) throws Exception {

        Field[] fields=obj.getClass().getFields();
        for (Field field : fields) {
            //字节码是唯一的,所以用"=="
            if (field.getType()==String.class) {
                String oldValue=(String) field.get(obj);
                String newValue=oldValue.replace('b', 'a');
                field.set(obj, newValue);
            }
        }
    }

}
class TestArguments{
    public static void main(String[] args) {
        for (String arg : args) {
            System.out.println(arg);
        }
    }
}

4.集合框架
需要写一个配置文件,存入要放入的类。集合在调用时,不知道创建对象的名字,需要在配置文件中获取。这时需要用反射。
代码如下:

package demo;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Collection;
import java.util.Properties;

public class ReflectTest {

    /**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
        //读取配置文件
        InputStream ips=new FileInputStream("config.properties");
        Properties prop=new Properties();
        prop.load(ips);//将键值对存入集合
        ips.close();//关闭资源
        String className=prop.getProperty("className");
        //new 一个对象
        Collection collections =(Collection) Class.forName(className).newInstance();

        //Collection collections = new HashSet();
        ReflectPoint pt1=new ReflectPoint(3, 3);
        ReflectPoint pt2=new ReflectPoint(5,5);
        ReflectPoint pt3=new ReflectPoint(3,3);

        collections.add(pt1);
        collections.add(pt2);
        collections.add(pt3);
        collections.add(pt1);
//      pt1.y=7;
//      collections.remove(pt1);

        System.out.println(collections.size());
    }

}

package demo;

public class ReflectPoint {
    private int x;
    public int y;

    public String str1="ball";
    public String str2="baskeball";
    public String str3="itcast";
    public ReflectPoint(int x, int y) {
        super();
        this.x = x;
        this.y = y;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + x;
        result = prime * result + y;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ReflectPoint other = (ReflectPoint) obj;
        if (x != other.x)
            return false;
        if (y != other.y)
            return false;
        return true;
    }

    public String toString(){
        return str1+"::"+str2+"::"+str3;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值