反射与注解;枚举

复制代码
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @program: FirstDemo
 * @description: Java反射学习
 * @author: GuoTong
 * @create: 2020-08-25 15:47
 **/
@SuppressWarnings("all")
public class TestReflection {
    public static void main(String[] args) throws Exception {
        //获取 Person  的字节码对象,由Java虚拟机由Class创建出来的,描述 Person 类结构的对象。
        //方式一:
        Person person = new Person("郭童", 23);
        System.out.println("反射之后" + person);
        //方式二
        Class<?> person2 = Class.forName("Person");
        Object obj1 = person2.newInstance();
        //方式三:
        Constructor<?> declaredConstructor1 = person2.getDeclaredConstructor();
        Object obj2 = declaredConstructor1.newInstance();
        //方式四

        Class<? extends Person> personClass = person.getClass();

        //getDeclaredFields||getDeclaredField;获取当前类的
        //getFile|| getFiles  是获得能够根据权限修饰符拿到的数据。可以获取穿透。
        //获取里面的属性(成员变量)
       /* Field[] declaredFields = personClass.getDeclaredFields();
        for (Field field : declaredFields) {
            System.out.println(field);
        }*/
        //操作成员变量:
        Field name = personClass.getDeclaredField("name");
        //成员变量赋值的时候,set的时候需要绑定当前对象。另一个参数为值。
        // name.set(person,"李四");//不过这里会报错,private修饰的。不能这样去改变
        // Class TestReflection can not access a member of class Person with modifiers "privat
        //暴力设置
        name.setAccessible(true);//private修饰的。暴力访问
        name.set(person, "李四");
        System.out.println("反射之后" + person);
        System.out.println("获取所有的方法:------------------不可穿透型");
        //获取所有的方法
        Method[] declaredMethods = personClass.getDeclaredMethods();
        for (Method method : declaredMethods) {
            System.out.println(method);
        }
        //得到需要被调用方法
        Method sayChinese = personClass.getDeclaredMethod("sayChinese");
        sayChinese.invoke(person);//调用方法
        //带参数的,拿的话需要定制形参类型。
        Method sayChinese2 = personClass.getDeclaredMethod("sayChineseDe", String.class);
        sayChinese2.invoke(person, "李四");//调用方法
        //private修饰的方法也可以暴力访问
        //method.setAccessible(true);

        System.out.println("获取构造器------------------");
        //构造器
        Constructor<?>[] declaredConstructors = personClass.getDeclaredConstructors();
        for (Constructor<?> constructor : declaredConstructors) {
            System.out.println(constructor);
        }
        //获取带参数的构造器
        Constructor<? extends Person> declaredConstructor = personClass.getDeclaredConstructor(String.class, int.class);
        System.out.println(declaredConstructor);
        //利用拿到的构造器创建对象
        Person person1 = declaredConstructor.newInstance("网吧", 32);
        System.out.println(person1);


    }


}
@SuppressWarnings("all")
class Person {
    private String name;
    private int age;

    public Person() {
    }

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

    public void sayChinese() {
        System.out.println("说中文");
    }

    public void sayChineseDe(String name) {
        System.out.println("说中文" + name);
    }

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

    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;
    }
}
复制代码

注解:

复制代码
import java.lang.annotation.*;
import java.lang.reflect.Method;

/**
 * @program: FirstDemo
 * @description: 注解相关学习:@interface自定义注解
 * 定义新的 Annotation 类型使用 @interface 关键字
 * 自定义注解自动继承了 java.lang.annotation.Annotation 接口
 * <p>
 * 元注解:@Retention,声明该注解作用范围,生命周期
 * RetentionPolicy.SOURCE :在源文件中有效(即源文件保留),编译器直接丢弃这种策略的注释
 * RetentionPolicy.CLASS :在class文件中有效(即class保留), 当运行 Java 程序时, JVM 不会保
 * 留注解。 这是默认值
 * RetentionPolicy.RUNTIME :在运行时有效(即运行时保留),当运行Java程序时, JVM会保留注
 * 释。程序可以通过反射获取该注释。
 * @Target 用于修饰 Annotation 定义, 用于指定被修饰的 Annotation 能用于修饰哪些程序元素。
 * Class, interface (including annotation type), or enum declaration
 * ElementType.TYPE
 * Field declaration (includes enum constants)
 * ElementType.FIELD,
 * Method declaration
 * ElementType.METHOD
 * @Documented 用于指定被该元 Annotation 修饰的 Annotation 类将被javadoc工具提取成文档。默认情况下,
 * javadoc是不包括注解的。
 * @Inherited 被它修饰的 Annotation 将具有继承性。如果某个类使用了被@Inherited 修饰的 Annotation, 则其子类
 * 将自动具有该注解。
 * @author: GuoTong
 * @create: 2020-08-26 08:32
 **/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
@Documented
@Inherited
public @interface TestAnnotation {
    String name() default "GuoTong";

    int age() default 10;

    String value();

}

class TestAnnotationS {
    public static void main(String[] args) throws NoSuchMethodException {
        Tree tree = new Tree();

        tree.say("x");
        //反射+注解
        Class<? extends Tree> clazz = tree.getClass();//获取该对象的字节码对象
        Method say = clazz.getDeclaredMethod("say", String.class);//获取到指定方法
        TestAnnotation annotation = say.getAnnotation(TestAnnotation.class);//获取方法上的注解
        String value = annotation.value();//获取注解的值
        System.out.println(" " + value);

    }
}

class Tree {
    @TestAnnotation("World")
    public void say(String value) {
        System.out.print("Hello");
    }
}
复制代码

枚举:

复制代码
/**
 * @program: FirstDemo
 * @description: 枚举
 * @author: GuoTong
 * @create: 2020-08-26 16:12
 **/
public enum  Enums {
    SPRING("晴天"),//枚举的狗仔器
    AUTUMN("阴天"),
    WINTER("刮风那天"),
    SUMMER("雨天");
    private String name;

    Enums(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}
class EnumTest{
    public static void main(String[] args) {
        for (Enums value : Enums.values()) {
            System.out.println(value);
        }
    }
}
复制代码

类加载

复制代码
/**
 * @program: FirstDemo
 * @description: 类加载器
 * @author: GuoTong
 * @create: 2020-08-25 17:02
 **/
public class ClassLoaderTest {
    public static void main(String[] args) throws ClassNotFoundException {
        //1.获取一个系统类加载器
        ClassLoader classloader = ClassLoader.getSystemClassLoader();
        System.out.println(classloader);
        //2.获取系统类加载器的父类加载器,即扩展类加载器
        classloader = classloader.getParent();
        System.out.println(classloader);
        //3.获取扩展类加载器的父类加载器,即引导类加载器
        classloader = classloader.getParent();
        System.out.println(classloader);//null,为什么:因为它是由C++编写的
        //打印为null,是jvm提示我们,前面已经到了java世界的尽头了。
        //4.测试当前类由哪个类加载器进行加载
        classloader = Class.forName("ClassLoaderTest").getClassLoader();
        System.out.println(classloader);

    }
}
复制代码

 

posted on   白嫖老郭  阅读(83)  评论(0编辑  收藏  举报

编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示