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

Java笔记:反射

时间:2018-03-07 13:28:36      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:cto   pos   构造   val   创建   通过   stringbu   close   display   

一、基础知识

Class是泛型超类,封装了类或接口运行时的状态。Class是Java中的反射中心,可以在运行时查找类的信息。

技术分享图片
class Solution {
    public static void main(String[] args) throws ClassNotFoundException {
        Class c = String.class;//通过类文字获取
        c = "Hello World".getClass();//通过getClass获取
        c = Class.forName("String");//通过forName获取
        c = Class.forName("String", false, Solution.class.getClassLoader());
    }
}
View Code

 

二、类反射

技术分享图片
import java.lang.reflect.Modifier;
import java.lang.reflect.TypeVariable;
import java.util.List;

class Solution {
    public static void main(String[] args) {
        Class c = List.class;

        int modifier = 0;//修饰符
        if (c.isInterface())
            modifier = c.getModifiers() & Modifier.interfaceModifiers();
        else modifier = c.getModifiers() & Modifier.classModifiers();
        System.out.println(Modifier.toString(modifier));

        TypeVariable<?>[] types = c.getTypeParameters();//泛型参数
        for (TypeVariable t : types)
            System.out.println(t.getTypeName());

        Class[] interfaces = c.getInterfaces();//实现接口
        for (Class i : interfaces)
            System.out.println(i);
    }
}
View Code


三、字段反射

Field可获取类中的字段信息。

技术分享图片
import java.lang.reflect.Field;

class Solution {
    public static void main(String[] args) {
        Class<String> c = String.class;
        Field[] fields = c.getFields();

        for (Field field : fields)
            System.out.println(field);
        //public static final java.util.Comparator java.lang.String.CASE_INSENSITIVE_ORDER
    }
}
View Code

 

四、方法反射

技术分享图片
import java.lang.reflect.*;

class Solution {
    static String getModifiers(Executable exec) {
        int modifier = exec.getModifiers();
        if (exec instanceof Method)
            modifier &= Modifier.methodModifiers();
        else if (exec instanceof Constructor)
            modifier &= Modifier.constructorModifiers();
        return Modifier.toString(modifier);
    }

    static String getParameters(Executable exec) {
        Parameter[] parameters = exec.getParameters();
        StringBuilder str = new StringBuilder();
        for (Parameter parameter : parameters)
            str.append(parameter + " ");
        return str.toString();
    }

    static String getExceptions(Executable exec) {
        StringBuilder str = new StringBuilder();
        Class[] cs = exec.getExceptionTypes();
        for (Class c : cs)
            str.append(c + " ");
        return str.toString();
    }

    public static void main(String[] args) {
        Class<Integer> c = Integer.class;
        Method[] methods = c.getDeclaredMethods();//不包括从超类中继承的方法
        for (Method method : methods) {
            System.out.println(method.getName());
            System.out.println(getModifiers(method));
            System.out.println(getParameters(method));
            System.out.println(getExceptions(method));
        }
    }
}
View Code

 

五、反射对象创建

无参构造函数。

技术分享图片
class MyClass {
    MyClass() {
        System.out.println("Constructor called");
    }
}

class Solution {
    public static void main(String[] args) {
        Class<MyClass> c = MyClass.class;
        try {
            MyClass o = c.newInstance();
            System.out.println(o);
        } catch (InstantiationException | IllegalAccessException exc) {
            exc.printStackTrace();
        }
    }
}
View Code

带参构造函数。

技术分享图片
import java.lang.reflect.Constructor;

class MyClass {
    MyClass(int i, String s) {
        System.out.println("Constructor called");
        System.out.println(i);
        System.out.println(s);
    }
}

class Solution {
    public static void main(String[] args) {
        Class<MyClass> c = MyClass.class;
        try {
            Constructor<MyClass> cons = c.getConstructor(int.class, String.class);//只能调用public的方法
            cons = c.getDeclaredConstructor(int.class, String.class);//可以调用本类声明的所有方法
            MyClass o = cons.newInstance(0, "Hello World");
            System.out.println(o);
        } catch (Exception exc) {
            exc.printStackTrace();
        }
    }
}
View Code

反射调用方法。

技术分享图片
import java.lang.reflect.Method;

class MyClass {
    public static void print(String s) {
        System.out.println(s);
    }
}

class Solution {
    public static void main(String[] args) {
        Class<MyClass> c = MyClass.class;
        try {
            MyClass o = c.newInstance();
            Method method = c.getMethod("print", String.class);
            method.invoke(o, "Hello World");
        } catch (Exception exc) {
            exc.printStackTrace();
        }
    }
}
View Code

 

六、反射字段访问

技术分享图片
import java.lang.reflect.Field;

class MyClass {
    public String str = "Hello World";
}

class Solution {
    public static void main(String[] args) {
        Class<MyClass> c = MyClass.class;
        try {
            MyClass o = c.newInstance();
            Field name = c.getField("str");
            String value = (String) name.get(o);
            System.out.println(value);

            name.set(o, "Hello World");
            value = (String) name.get(o);
            System.out.println(value);
        } catch (Exception exc) {
            exc.printStackTrace();
        }
    }
}
View Code

访问非可访问字段、方法和构造函数。

技术分享图片
import java.lang.reflect.Field;

class MyClass {
    private String str = "Hello World";
}

class Solution {
    public static void main(String[] args) {
        Class<MyClass> c = MyClass.class;
        try {
            MyClass o = c.newInstance();
            Field str = c.getDeclaredField("str");
            if (!str.isAccessible())
                str.setAccessible(true);
            String value = (String) str.get(o);
            System.out.println(value);
        } catch (Exception exc) {
            System.out.println(exc.getMessage());
        }
    }
}
View Code


七、数组反射

技术分享图片
import java.lang.reflect.Array;

class Solution {
    public static void main(String[] args) {
        try {
            int[] ar = (int[]) Array.newInstance(int.class, 10);
            for (int i = 0; i < 10; i++)
                Array.set(ar, i, i);
            for (int i = 0; i < 10; i++)
                System.out.println(Array.get(ar, i));
        } catch (Exception exc) {
            System.out.println(exc.getMessage());
        }
    }
}
View Code

获取数组维度。

技术分享图片
import java.lang.reflect.Array;

class Solution {
    public static void main(String[] args) {
        try {
            int[][] arr = (int[][]) Array.newInstance(int.class, 5, 5);
            Class c = arr.getClass();
            int i = 0;
            while (c.isArray()) {
                c = c.getComponentType();
                i++;
            }
            System.out.println(i);
        } catch (Exception exc) {
            System.out.println(exc.getMessage());
        }
    }
}
View Code

扩展数组。

技术分享图片
import java.lang.reflect.Array;
import java.util.Arrays;

class Solution {
    static Object extend(Object oldArr) {
        int oldLength = Array.getLength(oldArr);
        int newLength = oldLength * 2;
        Class c = oldArr.getClass();
        Object newArr = Array.newInstance(c.getComponentType(), newLength);
        System.arraycopy(oldArr, 0, newArr, 0, oldLength);
        return newArr;
    }

    public static void main(String[] args) {
        int[] arr = new int[5];
        for (int i = 0; i < arr.length; i++)
            arr[i] = i;
        System.out.println(Arrays.toString(arr));
        arr = (int[]) extend(arr);
        for (int i = 5; i < 10; i++)
            arr[i] = i;
        System.out.println(Arrays.toString(arr));
    }
}
View Code

 

Java笔记:反射

标签:cto   pos   构造   val   创建   通过   stringbu   close   display   

原文地址:https://www.cnblogs.com/arseneyao/p/8463334.html

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