Java 反射

package com.city.yf.reflector;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.Arrays;

public class Test {

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {

        class PartClass {

        }

        Class cls = Class.forName("com.city.yf.reflector.User");
        System.out.println("name:" + cls.getName());
        System.out.println("canonicalName:" + cls.getCanonicalName());
        System.out.println("modifier:" + cls.getModifiers());
        System.out.println("modifier:" + Modifier.toString(cls.getModifiers()));
        System.out.println("simpleName:" + cls.getSimpleName());
        System.out.println("typeName:" + cls.getTypeName());
        System.out.println("annotation:" + cls.isAnnotation());// 注解
        System.out.println("annotationOf:" + cls.isAnnotationPresent(SuppressWarnings.class));
        System.out.println("anonymous:" + cls.isAnonymousClass());
        System.out.println("isArray:" + cls.isArray());
        System.out.println("isArray:" + new User[] {}.getClass().isArray());
        System.out.println("assignableFrom:" + People.class.isAssignableFrom(User.class));
        System.out.println("isEnum:" + cls.isEnum());
        System.out.println("isInstance:" + cls.isInstance(new User()));
        System.out.println("isInterface:" + cls.isInterface());
        System.out.println("isLocalClass:" + PartClass.class.isLocalClass());// 当且仅当基础类是局部类
        System.out.println("isMemberClass:" + InnerClass.class.isMemberClass());// 成员内部类
        System.out.println("isPrimitive:" + cls.isPrimitive());// 基本数据类型,非他们的包装类
        System.out.println("isPrimitive:" + Integer.TYPE.isPrimitive() + Integer.class.isPrimitive());// Integer.Type==int.class
        System.out.println("isSynthetic:" + cls.isSynthetic());// Proxies. TODO
        System.out.println("asSubClass:" + cls.asSubclass(People.class));// cls转换为people的子类
        System.out.println("case:" + ((User) cls.cast(new User())).age);
        System.out.println("getAnnotatedInterfaces:");
        Arrays.asList(cls.getAnnotatedInterfaces()).stream().forEach(System.out::println);
        System.out.println("getAnnotatedSuperclass:" + cls.getAnnotatedSuperclass());
        System.out.println("componentType:" + new String[] {}.getClass().getComponentType());

        System.out.println("getConstructors:" + cls.getConstructors().length);
        Constructor[] constructors = cls.getConstructors();
        for (Constructor constructor : constructors) {
            if (constructor.getParameterCount() > 0) {
                User user = (User) constructor.newInstance("F");
                System.out.println(user.age + "\t" + user.name);
            } else {
                User user = (User) constructor.newInstance();
                System.out.println(user.age + "\t" + user.name);
            }
        }
        System.out.println(((User) cls.getConstructor(String.class).newInstance("hahaha")).name);

        Field[] fields = cls.getDeclaredFields();// 返回全部字段,不包含继承的
        for (Field field : fields) {
            String name = field.getName();
            String modifier = Modifier.toString(field.getModifiers());
            Class fieldCls = field.getType();
            System.out.println(String.format("%s %s %s", modifier, fieldCls.toString(), name));
        }
        fields = cls.getFields();// 返回 public 字段
        for (Field field : fields) {
            String name = field.getName();
            String modifier = Modifier.toString(field.getModifiers());
            Class fieldCls = field.getType();
            System.out.println(String.format("%s %s %s", modifier, fieldCls.toString(), name));
        }
        User user = new User();
        user.age = 10;
        user.name = "hyx";
        Field idField = cls.getDeclaredField("id");
        idField.setAccessible(true);
        System.out.println(idField.get(user));

        Method[] methods = cls.getDeclaredMethods();
        for (Method method : methods) {
            String name = method.getName();
            Type[] paramTypes = method.getGenericParameterTypes();
            Type returnType = method.getGenericReturnType();
            String modifier = Modifier.toString(method.getModifiers());
            System.out.print(modifier + " " + returnType.toString() + " " + name + "( ");
            Arrays.asList(paramTypes).stream().forEach(i -> System.out.print(i + ","));
            System.out.println(")");
        }
        Method method = cls.getMethod("test4", null);//only public
        String result = (String) method.invoke(new User());
        System.out.println("result of invoking test4:" + result);
        
        method = cls.getDeclaredMethod("test2", null);//all methods
        method.setAccessible(true);
        method.invoke(new User());
    }

    class InnerClass {

    }

    interface ITest {

    }
}

你可能感兴趣的:(Java 反射)