黑马程序员————————反射

反射就是把java类中的各种成分映射成相应的java类。例如,一个java类中用一个Class类的对象来表示,一个类中的组成部分:成员变量、方法、构造方法、包等等信息也是用一个个的java类来表示,就像汽车是一个类,发动机、变速箱等也是一个个的类。表示java类的Class类显然要提供一系列的方法,来获得其中的变量、方法、构造方法、修饰符、包等信息,这些信息就是用相应的类的实例对象来表示,它们就是Field、Method、Constructor、Packet等。

    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 ReflectTest {  

        /** 
         * @param args 
         */  
        public static void main(String[] args) throws Exception{  
            // TODO Auto-generated method stub  
            String str = "abc";  
            Class cls1 = String.class;  
            Class cls2 = str.getClass();  
            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());  

            //new String(new StringBuffer("abc"));  
            Constructor constructor1 = String.class.getConstructor(StringBuffer.class);  
            String str1 = (String)constructor1.newInstance(new StringBuffer("abc"));  
            System.out.println(str1.charAt(1));  

            ReflectPoint pt1 = new ReflectPoint(3,4);  
            Field fieldY = pt1.getClass().getField("y");  
            //field的值是多少?是5,不对。fieldY不是对象身上的变量,而是类上的,要用它去取某个对象上对应的值。  
            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 methodCharAt = String.class.getMethod("charAt", int.class);  
            System.out.println(methodCharAt.invoke(str, 1));  
            System.out.println(methodCharAt.invoke(str, new Object[]{0}));  


             //用反射方式执行某个类中的main方法。  
            //TestArguments.main(new String[]{});  
            String startingClassName = args[0];  
            Method mainMethod = Class.forName(startingClassName).getMethod("main", String[].class);  
            mainMethod.invoke(null, (Object)new String[]{"11","223","343"});  
            //或者这种方式  mainMethod.invoke(null, new Object[]{new String[]{"11","223","343"}});  

            //数组的反射。  
            int[] a1 = new int[]{1,2,3};  
            int[] a2 = new int[4];  
            int[][] a3 = new int[2][3];  
            String[] a4 = new String[]{"g","d","c","a"};  
            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(a1.getClass().getSuperclass().getName());  
            Object  aObj1 = a1;  
            Object aObj2 = a4;  
            //Object[] aObj3 = a1;基本数据类型不属于Object  
            Object[] aObj4 = a3;  
            Object[] aObj5 = a4;  
            System.out.println(a1);  
            System.out.println(a4);  
            System.out.println(Arrays.asList(a1));  
            System.out.println(Arrays.asList(a4));  
            printObject(a4);  
            printObject("dfe");  
        }  

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

        }  

        private static void changeStringValue(Object obj)throws Exception {  
            // TODO Auto-generated method stub  
            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);  
            }  
        }  
    }  
    package cn.itcast.day1;  

    import java.util.Date;  

    public class ReflectPoint {  
            private Date birthday = new Date();  
            private int x;  
            public int y;  
            public String str1 = "ball";  
            public String str2 = "basketball";  
            public String str3 = "itcast";  
            public Date getBirthday() {  
                return birthday;  
            }  
            public void setBirthday(Date birthday) {  
                this.birthday = birthday;  
            }  
            public ReflectPoint(int x, int y) {  
                super();  
                this.x = x;  
                this.y = y;  
            }  
            public int getX() {  
                return x;  
            }  
            public void setX(int x) {  
                this.x = x;  
            }  
            public int getY() {  
                return y;  
            }  
            public void setY(int y) {  
                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;  
            }  

    }

你可能感兴趣的:(黑马程序员————————反射)