java 反射获取类结构

通过反射获取类的注解信息

package com.seven.classTest;

import java.lang.annotation.*;
import java.lang.reflect.Field;
//通过反射获取类的注解信息
public class TestAnnotation {
    public static void main(String[] args) throws Exception {

        //通过反射获取类的注解信息
        Class c1 = Person01.class;

        Annotation declaredAnnotation = c1.getDeclaredAnnotation(TableAnnotation.class);
        TableAnnotation tableAnnotation = (TableAnnotation) declaredAnnotation;
        System.out.println(tableAnnotation.value());


        //获取属性注解信息
        Field name = c1.getDeclaredField("name");

        FieldAnnotation declaredAnnotation1 = name.getDeclaredAnnotation(FieldAnnotation.class);
        FieldAnnotation fieldAnnotation = declaredAnnotation1;
        System.out.println(fieldAnnotation.fieldName());
        System.out.println(fieldAnnotation.fieldType());
        System.out.println(fieldAnnotation.length());

    }
}
@TableAnnotation("db_person")
class Person01{
    @FieldAnnotation(fieldName = "id",fieldType = "varchar",length = 10)
    private int id;
    @FieldAnnotation(fieldName = "name",fieldType = "varchar",length = 5)
    private String name;

    public Person01() {
    }

    public Person01(int 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;
    }


    @Override
    public String toString() {
        return "Person01{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableAnnotation{
    String value();
}

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldAnnotation{
    String fieldName();
    String fieldType();
    int length();
}

通过反射获取类的结构

package com.seven.classTest;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;


public class TestClassGet {
    public static void main(String[] args) throws Exception {
        Class c1 = Class.forName("com.seven.classTest.Dog");

        //获取属性
//        Field id = c1.getField("id");//id属性私有,不能获取
        Field age =c1.getField("age");//age属性是公共的public修饰的,可以获得
        Field id1 = c1.getDeclaredField("id");//用getDeclaredField就可以获取私有公共属性
        System.out.println(age);
        System.out.println(id1);
        //获取对象的公共属性
        Field[] fields = c1.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }
        //获取对象的所有属性
        Field[] fields1 = c1.getDeclaredFields();
        for (Field field : fields1) {
            System.out.println(field);
        }

        System.out.println("---------------------------------------------------");

        //获取对象的方法
        Method getId = c1.getMethod("getId", null);//不能去获取私有的方法
        Method setId = c1.getMethod("setId", int.class);
        System.out.println(getId);
        System.out.println(setId);

        System.out.println("---------------------------------------------------");


        //获取构造器(getDeclaredConstructors:获取所有的构造器)
        Constructor[] constructors = c1.getConstructors();//获取公共的构造器集合
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
        //获取指定的构造器
        Constructor constructor = c1.getConstructor(int.class, String.class, int.class);
        System.out.println(constructor);


    }
}
class Dog{
    private int id;
    private String name;
    public int age;

    public Dog() {
    }

    public Dog(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    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;
    }

    private void test(){}

    @Override
    public String toString() {
        return "Dog{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

通过反射来操作对象

package com.seven.classTest;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestClassNew {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        Class c1 = Class.forName("com.seven.classTest.Dog");
        //1.通过newInstance来new一个Dog对象
        Dog dog = (Dog) c1.newInstance();
        System.out.println(dog.toString());

        //2.通过构造器的newInstance方法new一个Dog对象
        Constructor constructor = c1.getDeclaredConstructor(int.class, String.class, int.class);

        Dog dog1 = (Dog) constructor.newInstance(12,"lili",43);
        System.out.println(dog1.toString());


        //通过反射得到一个方法,执行
        Object o = c1.newInstance();
        Dog dog2 = (Dog) o;

        Method setName = c1.getMethod("setName", String.class);
        setName.invoke(dog2,"wuwan");
        System.out.println(dog2);

        //通过反射 直接给类的对象 属性赋值:
        Field name = c1.getDeclaredField("name");
        name.setAccessible(true);//设置关闭程序的安全检测(对私有属性访问时不能直接访问时设置)
        name.set(dog2,"seven");
        System.out.println(dog2);

    }
}

通过反射获取泛型

package com.seven.classTest;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
//通过反射获取泛型
public class TestGeneric {
    public void test01(Map<String,Dog> dogMap, List<Dog> dogList ){
        System.out.println("test01");
    }
    public Map<String,Dog> test02(){
        System.out.println("test02");
        return null;
    }

    public static void main(String[] args) throws Exception {
    //通过反射获取泛型
        Method test01 = new TestGeneric().getClass().getMethod("test01", Map.class, List.class);
        Method test02 = new TestGeneric().getClass().getMethod("test02");
        //获取参数泛型集合
        Type[] parameterTypes = test01.getGenericParameterTypes();
        for (Type parameterType : parameterTypes) {
            System.out.println(parameterType);
            if (parameterType instanceof ParameterizedType)//如果这个参数值是个标准的泛型参数
            {
                Type[] arguments = ((ParameterizedType) parameterType).getActualTypeArguments();
                for (Type argument : arguments) {
                    System.out.println("-----"+argument);
                }
            }
        }

        //获取泛型的返回值
        Type genericReturnType = test02.getGenericReturnType();
        System.out.println(genericReturnType);
        if (genericReturnType instanceof ParameterizedType){
            Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
            for (Type actualTypeArgument : actualTypeArguments) {
                System.out.println("========"+actualTypeArgument);
            }
        }

    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值