注解和反射


注解和反射

import java.lang.reflect.Constructor;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Objects;

public class Main {
    public static void main(String[] args) throws Exception{
//        1.获得Person的反射类
        Class<Person> personClass = Person.class;


//      2.获取构造器
        Constructor<Person> declaredConstructor = personClass.getDeclaredConstructor(String.class,Integer.class,boolean.class);
        declaredConstructor.setAccessible(true); //运行修改   private需要声明
        Person person = declaredConstructor.newInstance("lhq",22,true);
        System.out.println(person);
        /*
        Person{name='lhq', age=22, sex=true}
         */

//      3.获取属性,直接赋值
        Field name = personClass.getDeclaredField("name");
        name.setAccessible(true);
        name.set(person,"华强");
        System.out.println(person);
        /*
        Person{name='lhq', age=22, sex=true}
        Person{name='华强', age=22, sex=true}
         */

//      4.获取方法
        Method show = personClass.getDeclaredMethod("show");
        show.setAccessible(true);
        show.invoke(person);
        /*
        Person{name='lhq', age=22, sex=true}
        Person{name='华强', age=22, sex=true}
        你好
         */
//        4-2  再取列一个 有参数的方法
        Method setAge = personClass.getDeclaredMethod("setAge", Integer.class);
        setAge.setAccessible(true);
        setAge.invoke(person,21);
        System.out.println(person);  //Person{name='华强', age=21, sex=true}
    }
}

class Person {
    private String name;
    private Integer age;
    private boolean sex;

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return sex == person.sex &&
                Objects.equals(name, person.name) &&
                Objects.equals(age, person.age);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age, sex);
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public boolean isSex() {
        return sex;
    }

    public void setSex(boolean sex) {
        this.sex = sex;
    }

    private Person() {
    }

    private Person(String name, Integer age, boolean sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    private void show(){
        System.out.println("你好");
    }
}

元注解

@Target(value = {ElementType.METHOD/*允许放在方法上面*/, ElementType.TYPE/*允许放在类上面*/})  /*你的注解作用范围定义*/
//runtime> class > source
@Retention(value = RetentionPolicy.RUNTIME /*代码在运行时有效*/     /*,class: 编译有效 , source: 源码有效)*/)
//表示是否生成在javaDoc
@Documented
//表示子类可以继承父类的注解
@Inherited
@interface MyAnnotation {

}

自定义注解 @interface


@Target(value = {ElementType.METHOD,ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME )
@interface MyAnnotation {
    // 注解的参数:  参数类型+参数名字+();
    String name();
}

反射

package lhq;

/**
 * @author 刘华强
 * @Classname lhq.Main
 * @Description TODO
 * @Date 2021/1/12 16:04
 */
public class Main {
    public static void main(String[] args) throws ClassNotFoundException {
        Class<?> c1 = Class.forName("lhq.User");
        Class<User> c2 = User.class;
        User user = new User();
        Class<? extends User> c3 = user.getClass();
        System.out.println(c1.hashCode());
        System.out.println(c2.hashCode());
        System.out.println(c3.hashCode());
        /*
         * 460141958
         * 460141958
         * 460141958
         */
      }
}

public class test1 {
    public static void main(String[] args) {
        Class c1 = Object.class; //类
        Class c2 = Comparable.class; //接口
        Class c3 = String[].class; //-维数组
        Class c4 = int[][].class; //二维数组
        Class c5 = Override.class; //注解
        Class c6 = ElementType.class; //枚举
        Class c7 = Integer.class; //基本数据类型
        Class c8 = void.class; //void
        Class c9 = Class.class; //Class
        System.out.println(c1);
        System.out.println(c2);
        System.out.println(c3);
        System.out.println(c4);
        System.out.println(c5);
        System.out.println(c6);
        System.out.println(c7);
        System.out.println(c8);
        System.out.println(c9);
        /*
        class java.lang.Object
        interface java.lang.Comparable
        class [Ljava.lang.String;
        class [[I
        interface java.lang.Override
        class java.lang.annotation.ElementType
        class java.lang.Integer
        void
        class java.lang.Class
        Process finished with exit code 0
         */
    }
}

image-20210112162024854

class A{

    static {
        System.out.println("静态代码块加载");
        m = 200;
    }

    public static int m = 100;

    public A() {
        System.out.println("构造函数加载");
    }
}
/*
静态代码块加载
构造函数加载
100
*/




class A{
    public static int m = 100;

    static {
        System.out.println("静态代码块加载");
        m = 200;
    }


    public A() {
        System.out.println("构造函数加载");
    }
}
/*
静态代码块加载
构造函数加载
200
*/    

image-20210112165545865

image-20210112170000445

获取方法

package com.lhq;

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

/**
 * @author 刘华强
 * @Classname ReflectTest
 * @Description TODO
 * @Date 2021/1/12 17:17
 */
@SuppressWarnings(value = "all")
public class ReflectTest {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
        Class<?> c1 = Class.forName("com.lhq.pojo.User");
        System.out.println(c1.getName()); //获得包名
        System.out.println(c1.getSimpleName()); //获得类名
        for (Field field : c1.getFields()) {
            System.out.println(field);
        }
        for (Field declaredField : c1.getDeclaredFields()) {
            System.out.println(declaredField);
        }
//        System.out.println(c1.getField("name"));
        System.out.println(c1.getDeclaredField("name"));

        for (Method declaredMethod : c1.getDeclaredMethods()) {
            System.out.println(declaredMethod);
        }

        for (Method method : c1.getMethods()) {
            System.out.println(method);
        }

        System.out.println(c1.getMethod("getName"));
        System.out.println(c1.getDeclaredMethod("getAge"));

        for (Constructor<?> constructor : c1.getConstructors()) {
            System.out.println(constructor);
        }
        for (Constructor<?> declaredConstructor : c1.getDeclaredConstructors()) {
            System.out.println(declaredConstructor);
        }

        System.out.println(c1.getDeclaredConstructor(String.class, Integer.class, Integer.class));
    }
}

修改方法

package com.lhq;

import com.lhq.pojo.User;

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

/**
 * @author 刘华强
 * @Classname ReflectTest
 * @Description TODO
 * @Date 2021/1/12 17:17
 */
@SuppressWarnings(value = "all")
public class ReflectTest2 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        Class c1 = Class.forName("com.lhq.pojo.User");
        User user = ((User) c1.newInstance());
        System.out.println(user);

        Constructor constructor = c1.getDeclaredConstructor(String.class, Integer.class, Integer.class);
        User user1 = (User) constructor.newInstance("lhq", 7, 18);
        System.out.println(user1);

        //通过反射调用方法
        User user2 = (User) c1.newInstance();
        Method setNameMothod = c1.getDeclaredMethod("setName", String.class);
        setNameMothod.invoke(user2,"刘华强");
        System.out.println(user2);

        User user3 = (User) c1.newInstance();
        Field nameField = c1.getDeclaredField("name");
        /*关闭程序的安全检测*/
        nameField.setAccessible(true);
        nameField.set(user3, "华强牛逼");
        System.out.println(user3);
    }
}

反射获得泛型

package com.lhq;

import com.lhq.pojo.User;

import java.lang.reflect.*;
import java.util.List;
import java.util.Map;

/**
 * @author 刘华强
 * @Classname ReflectTest
 * @Description TODO
 * @Date 2021/1/12 17:17
 */
@SuppressWarnings(value = "all")
public class ReflectTest3 {

    public void test1(Map<String, User> map, List<User> users) {
        System.out.println("test01");
    }

    public Map<String, User> test2() {
        System.out.println("test02");
        return null;
    }

    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        Class<ReflectTest3> c1 = ReflectTest3.class;

        Method method1 = c1.getDeclaredMethod("test1", Map.class, List.class);
        for (Type genericParameterType : method1.getGenericParameterTypes()) {
            System.out.println(genericParameterType);
            if(genericParameterType instanceof ParameterizedType){
                Type[] types = ((ParameterizedType) genericParameterType).getActualTypeArguments();
                for (Type type : types) {
                    System.out.println(type);
                }
            }
        }

        Method method = c1.getDeclaredMethod("test2");
        Type type = method.getGenericReturnType();
        if (type instanceof ParameterizedType) {
            Type[] types = ((ParameterizedType) type).getActualTypeArguments();
            for (Type type1 : types) {
                System.out.println(type1);
            }
        }
    }
}

反射操作注解

public class Reflect2Annotation {
    public static void main(String[] args) throws NoSuchFieldException {
        Class<Student> c1 = Student.class;

        for (Annotation declaredAnnotation : c1.getDeclaredAnnotations()) {
            System.out.println(declaredAnnotation);
        }

        //获取注解的值
        Tableliu tableliu = c1.getDeclaredAnnotation(Tableliu.class);
        String value = tableliu.value();
        System.out.println(value);
        //获得指定注解的值
        Field declaredField = c1.getDeclaredField("name");
        declaredField.setAccessible(true);
        Fieldliu annotation = declaredField.getAnnotation(Fieldliu.class);
        System.out.println(annotation.columnName());
        System.out.println(annotation.type());
        System.out.println(annotation.length());

    }
}

@Tableliu(value = "lhq")
class Student {
    @Fieldliu(columnName = "lhq_id", type = "int", length = 10)
    private int id;
    @Fieldliu(columnName = "lhq_name", type = "String", length = 10)
    private String name;
    @Fieldliu(columnName = "lhq_age", type = "int", length = 3)
    private int age;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", 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;
    }

    public int getAge() {
        return age;
    }

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

    public Student() {
    }

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

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


@Target(value = {ElementType.FIELD})
@Retention(value = RetentionPolicy.RUNTIME)
@interface Fieldliu {
    String columnName();

    String type();

    int length();
}

实战1 (标识有注解的就运行)

@Target(value = ElementType.METHOD)
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Testinit {
}


public class DemoInit{
    @Testinit
    public void init(){
        System.out.println("1");
    }
    @Testinit
    public void init2(){
        System.out.println("233");
    }
}


public class Main {
    public static void main(String[] args) throws Exception{
        Class<?> aClass = Class.forName("com.lhq.Main.DemoInit");
        Method[] methods = aClass.getMethods();
        for (Method method : methods) {
            boolean annotationPresent = method.isAnnotationPresent(Testinit.class);
            if(annotationPresent){
                method.invoke(aClass.getConstructor(null).newInstance(null),null);
            }
        }
    }
}



文章作者: anlen123
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 anlen123 !
 上一篇
Ajax Ajax
Ajax导入jquery 下载连接 https://mp.weixin.qq.com/s/tB4YX4H59wYS6rxaO3K2_g AJAX = Asynchronous JavaScript and XML(异步的 JavaScri
2021-01-14 anlen123
下一篇 
nginx nginx
nginx反向代理 如果路径中带有edu就访问8001 如果路径中带有vod就访问8002 负载均衡 默认轮询算法 动静结合 docker 实战 首先,pull nginx镜像 docker pull nginx:latest
2021-01-11 anlen123
  目录