java反射溫習一下

來源:互聯網
上載者:User

標籤:

public class LoveReflect {    public static class Demo  implements Serializable{            }        public static void main(String[] arg) {        Demo demo = new Demo();        System.out.println(demo.getClass().getName());    }}

輸出

LoveReflect$Demo
ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
JDWP exit error AGENT_ERROR_NO_JNI_ENV(183): [../../../src/share/back/util.c:820]

 

import java.io.Serializable;import java.lang.reflect.Array;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.lang.reflect.Modifier;import java.util.HashMap;import java.util.Map;public class LoveReflect {    public static class SubClass implements Serializable {        private int id;        private String name;        public SubClass() {        }        public SubClass(Integer id, String name) {            this.id = id;            this.name = name;        }        public int getId() {            return id;        }        public void setId(int id) {            this.id = id;        }        public String getName() {            return name;        }        public void setName(String name) {            this.name = name;        }                public void subMethod() {            System.out.println("hello world");        }    }    public static void main(String[] arg) {        SubClass subClass = new SubClass();        //【案例1】通過名字取得類的聲明,再取得名字        System.out.println(subClass.getClass().getName());                Class<?> demo1;        try {            //【案例2】通過名字取得類的聲明            demo1 = Class.forName("LoveReflect$SubClass");            System.out.println(demo1.getName());            //【案例3】通過名字找到類的聲明,再建立執行個體            SubClass subClass2 = (SubClass) Class.forName("LoveReflect$SubClass").newInstance();            subClass2.setId(1);            subClass2.setName("aaaa");            System.out.println(subClass2.getName());            //【案例4】拿類的的建構函式new執行個體            Class<?>[] parameterTypes = {Integer.class,String.class};            Constructor constructor = Class.forName("LoveReflect$SubClass").getDeclaredConstructor(parameterTypes);            SubClass subClass3 = (SubClass)constructor.newInstance(2,"222222222222222222");            System.out.println(subClass3.getName());            //            改個屬性值            Field f = subClass3.getClass().getDeclaredField("name");            Class<?> type = f.getType();            System.out.println("field type="+type.getName());            int mod = f.getModifiers();            System.out.println("modify="+Modifier.toString(mod));                        f.setAccessible(true);            f.set(subClass3, "bbbbbbbbbbbbbbb");            System.out.println(subClass3.getName());                        Map<Integer,Method> methods = new HashMap<Integer,Method>();            Class<?>[] parameterTypes2 = {};            Method method = Class.forName("LoveReflect$SubClass").getDeclaredMethod("subMethod", parameterTypes2);                        //用執行個體調方法            method.invoke(subClass3, null);                        //通過反射處理數組            SubClass[] subClass_ = {new SubClass(1,"bbbbbbbbbbbbbbb"), subClass, subClass2, subClass3};            Class<?> arrayType = subClass_.getClass().getComponentType();            System.out.println("array type="+arrayType.getName());            System.out.println("array leangth="+Array.getLength(subClass_));            System.out.println("first one="+((SubClass)Array.get(subClass_, 0)).getName());            Array.set(subClass_, 0, subClass2);            System.out.println("first one="+((SubClass)Array.get(subClass_, 0)).getName());                        //修改數組的大小            SubClass[] newTemp=(SubClass[])arrayInc(subClass_,15);            System.out.println("array leangth="+Array.getLength(newTemp));            print(newTemp);        } catch (ClassNotFoundException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (InstantiationException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IllegalAccessException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (SecurityException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (NoSuchMethodException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IllegalArgumentException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (InvocationTargetException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (NoSuchFieldException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }               /**     * 修改數組大小     * */    public static Object arrayInc(Object obj,int len){        Class<?>arr=obj.getClass().getComponentType();        Object newArr=Array.newInstance(arr, len);        int co=Array.getLength(obj);        System.arraycopy(obj, 0, newArr, 0, co);        return newArr;    }    /**     * 列印     * */    public static void print(Object obj){        Class<?>c=obj.getClass();        if(!c.isArray()){            return;        }        System.out.println("數組長度為: "+Array.getLength(obj));        for (int i = 0; i < Array.getLength(obj); i++) {            System.out.print(Array.get(obj, i)+" ");        }    }}

 

java反射溫習一下

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.