java注解和反射

本文详细介绍了Java中的注解(元注解、自定义注解)及其使用,包括@Target和@Retention的含义。同时,阐述了反射的概念、优缺点,并展示了如何通过反射获取类的构造器、属性、方法等信息。此外,还演示了如何通过反射创建对象、调用方法和修改属性。最后,讲解了如何通过反射获取注解信息及其值。
摘要由CSDN通过智能技术生成

注解

  • 不是程序本身,可以对程序做出解释
  • 可以被其他程序读取
  • @注释名

元注解

负责注解其他注解
@target;@retention

自定义注解

package annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

public class Test01 {

    @Myannotation(name = "薛博",age = 1)
    public void test(){

    }
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface Myannotation{
    String name() default "";
    int age() default 0;
    String[] Schools() default "";
}

反射

reflection

优点:实现动态创建对象和编译,体现灵活性
缺点:对性能有影响

获取Class类实例
package reflection;
//测试class类创建方式
public class Test02 {
    public static void main(String[] args) throws ClassNotFoundException {

        Person person = new Student();
        System.out.println(person.name);

        //方式一:通过对象获得
        Class c1 = person.getClass();
        System.out.println(c1.hashCode());
        //方式二:forname
        Class c2 = Class.forName("reflection.Student");
        System.out.println(c2.hashCode());
        //方式三:通过类名.class
        Class c3 = Student.class;
        System.out.println(c3.hashCode());
        //方式四:基本内置类型的包装类都有一个Type属性
        Class c4 = Integer.TYPE;
        System.out.println(c4);

        //获得父类类型
        Class s1 = c1.getSuperclass();
        System.out.println(s1);
    }
}
class Person{
     public String  name;

    public Person() {
    }

    public Person(String name) {
        this.name = name;
    }

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

class Student extends Person{
     public Student(){
         this.name="学生";
     }
}
class Teacher extends Person{
    public Teacher(){
        this.name="老师";
    }
}

哪些类型可以有class对象

  • class:外部类,成员,局部内部类,匿名内部类
  • interface:接口
  • 【】数组
  • enum:枚举
  • annotation:注解
  • 基本数据类型
  • void
获取类的完整结构
package reflection;

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

//获得类的信息
public class Test04 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
     Class c1 = Class.forName("reflection.User");

//        User user = new User();
//          c1 =  user.getClass();


        //1.获得类的名字
        System.out.println(c1.getName());
        System.out.println(c1.getSimpleName());

        //2.获得类的属性
        Field[] fields = c1.getFields();//public的属性
        for (Field field : fields) {
            System.out.println(field);
        }

        Field[] declaredFields = c1.getDeclaredFields();//全部属性
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
        }

        //获得指定的属性
        System.out.println(c1.getDeclaredField("name"));

        //3.获得类的方法

        Method[] methods = c1.getMethods();//获得本类及其父类的全部public方法
        for (Method method : methods) {
            System.out.println("正常的"+method);
        }

        methods = c1.getDeclaredMethods();//获得本类的所有方法
        for (Method method : methods) {
            System.out.println("全部的"+method);
        }
        //获得指定的方法
        System.out.println(c1.getMethod("getName", null));
        System.out.println(c1.getMethod("setName", String.class));

        System.out.println("________________________________________________");
        //4.获得构造器
        Constructor[] constructor = c1.getConstructors();//获得public方法
        for (Constructor constructor1 : constructor) {
            System.out.println(constructor1);
        }
        Constructor[] constructor2 = c1.getDeclaredConstructors();//获得全部方法
        for (Constructor constructor1 : constructor2) {
            System.out.println(constructor1);
        }

        //获得指定的构造器
        Constructor constructor222 = c1.getConstructor(String.class, int.class, int.class);
        System.out.println("指定"+constructor222);
    }
}
反射创建对象
package reflection;

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

//通过反射创建对象
public class Test05 {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        //获得class对象
        Class c1 = Class.forName("reflection.User");
        //构造一个对象
//        User user= (User)c1.newInstance();//调用类的无参构造器
//        System.out.println(user);

//        //通过构造器创建对象
//        Constructor declaredConstructors = c1.getDeclaredConstructor(String.class, int.class, int.class);
//        User user2 = (User) declaredConstructors.newInstance("薛博",001,18);
//        System.out.println(user2);

        //通过反射调用普通方法
        User user3 = (User) c1.newInstance();
        Method setName = c1.getDeclaredMethod("setName", String.class);
        setName.invoke(user3,"薛");
        System.out.println(user3.getName());

        //通过反射操作属性
        User user4 = (User) c1.newInstance();
        Field name = c1.getDeclaredField("name");

        //不能直接操作私有属性
        name.setAccessible(true);//关闭安全检测
        name.set(user4,"薛博2");
        System.out.println(user4.getName());


    }
}
反射获取注解

```java
package reflection;

import java.lang.annotation.*;
import java.lang.reflect.Field;

//反射操作注解
public class Test06 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        Class  c1 = Class.forName("reflection.Student2");
        //通过反射获得注解
        Annotation[] annotations = c1.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }
        //获得注解的value的值
       TableKuang tableKuang = (TableKuang)c1.getAnnotation(TableKuang.class);
        System.out.println(tableKuang.value());
        //获得类指定的注解

        Field f = c1.getDeclaredField("name");
        FieldKuang annotation = f.getAnnotation(FieldKuang.class);
        System.out.println(annotation.columnName());
        System.out.println(annotation.type());
        System.out.println(annotation.length() );

    }

}


@TableKuang("db_student")
class Student2{

    @FieldKuang(columnName = "db_id", type = "int", length = 10)
    private int id;
    @FieldKuang(columnName = "db_age", type = "int", length = 10)
    private int age;
    @FieldKuang(columnName = "db_name", type = "varchar", length = 3)
    private String name;

    public Student2() {
    }

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

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

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


//类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableKuang{
    String value();
}

//属性的注解

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldKuang{
    String columnName();
    String type();
    int length();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值