注解
可以被其他程序(比如:编译器等)读取
@SuppressWarnings("all") //镇压警告
@Override //重写
@Deprecated //不推荐程序员使用或存在更好的方式,但可以使用
package com.company.annotation;
import java.lang.annotation.*;
//测试元注解
@MyAnnotation
public class Test01 {
public void test(){
}
}
//定义一个注解
//Target 表示我们的注解可以用在哪些地方
@Target(value = {ElementType.METHOD,ElementType.TYPE})
//Retention 表示我们的注解在什么地方还有效
@Retention(value = RetentionPolicy.RUNTIME)
//Documented 表示是否将我们的注解生成在JAVAdoc中
@Documented
//Inherited 子类可以继承父类的注解
@Inherited
@interface MyAnnotation{
}
自定义注解
package com.company.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
public class Test02 {
@MyAnnotation2
public void test(){}
@MyAnnotation3("YRZ")
public void test2(){}
}
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
//注解的参数:参数类型 + 参数名();
String name() default "";
int age() default 0;
int id() default -1; //如果默认值为-1,代表不存在
String[] school() default "清华大学";
}
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation3{
String value(); //只有一个值的情况下
}
反射
Reflection
package com.company.reflection;
public class Test01 {
public static void main(String[] args) throws ClassNotFoundException {
Class c1 = Class.forName("com.company.reflection.User");
System.out.println(c1);
Class c2 = Class.forName("com.company.reflection.User");
Class c3 = Class.forName("com.company.reflection.User");
Class c4 = Class.forName("com.company.reflection.User");
//一个类在内存中只有一个Class对象
//一个类被加载后,类的整个结构都会被封装在Class对象中
System.out.println(c2.hashCode());
System.out.println(c3.hashCode());
System.out.println(c4.hashCode());
}
}
//实体类:pojo、entity
class User{
private String name;
private int age;
private int id;
public User() {
}
public User(String name, int age, int id) {
this.name = name;
this.age = age;
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 int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", id=" + id +
'}';
}
}
得到Class类的几种方式
package com.company.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("com.company.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 c5 = c1.getSuperclass();
System.out.println(c5);
}
}
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 = "老师";
}
}
分析类初始化
类加载器
package com.company.reflection;
public class Test04 {
public static void main(String[] args) throws ClassNotFoundException {
//获取系统类加载器
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
System.out.println(systemClassLoader);
//获取系统类加载器的父类加载器-->扩展类加载器
ClassLoader parent = systemClassLoader.getParent();
System.out.println(parent);
//获取扩展类加载器的父类加载器-->根加载器(c/c++)
ClassLoader parent1 = parent.getParent();
System.out.println(parent1);
//测试当前类是被哪个加载器加载的
ClassLoader classLoader = Class.forName("com.company.reflection.Test04").getClassLoader();
System.out.println(classLoader);
//测试JDK内置的类是谁加载的
ClassLoader classLoader1 = Class.forName("java.lang.Object").getClassLoader();
System.out.println(classLoader1);
//如何获得系统类加载器可以加载的路径
System.out.println(System.getProperty("java.class.path"));
// D:\bishe\jdk8\jre\lib\charsets.jar;
// D:\bishe\jdk8\jre\lib\deploy.jar;
// D:\bishe\jdk8\jre\lib\ext\access-bridge-64.jar;
// D:\bishe\jdk8\jre\lib\ext\cldrdata.jar;
// D:\bishe\jdk8\jre\lib\ext\dnsns.jar;
// D:\bishe\jdk8\jre\lib\ext\jaccess.jar;
// D:\bishe\jdk8\jre\lib\ext\jfxrt.jar;
// D:\bishe\jdk8\jre\lib\ext\localedata.jar;
// D:\bishe\jdk8\jre\lib\ext\nashorn.jar;
// D:\bishe\jdk8\jre\lib\ext\sunec.jar;
// D:\bishe\jdk8\jre\lib\ext\sunjce_provider.jar;
// D:\bishe\jdk8\jre\lib\ext\sunmscapi.jar;
// D:\bishe\jdk8\jre\lib\ext\sunpkcs11.jar;
// D:\bishe\jdk8\jre\lib\ext\zipfs.jar;
// D:\bishe\jdk8\jre\lib\javaws.jar;
// D:\bishe\jdk8\jre\lib\jce.jar;
// D:\bishe\jdk8\jre\lib\jfr.jar;
// D:\bishe\jdk8\jre\lib\jfxswt.jar;
// D:\bishe\jdk8\jre\lib\jsse.jar;
// D:\bishe\jdk8\jre\lib\management-agent.jar;
// D:\bishe\jdk8\jre\lib\plugin.jar;
// D:\bishe\jdk8\jre\lib\resources.jar;
// D:\bishe\jdk8\jre\lib\rt.jar;
// D:\IDEA\net\study\out\production\study;
// D:\IDEA\IntelliJ IDEA 2020.1\lib\idea_rt.jar
}
}
获取运行时类的结构
package com.company.reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
//获得类的信息
public class Test05 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
Class c1 = Class.forName("com.company.reflection.User");
//获得类的名字
System.out.println(c1.getName());
System.out.println(c1.getSimpleName());
//获得类的属性
System.out.println("=======================================");
Field[] fields1 = c1.getFields(); //只能找到public属性
Field[] fields = c1.getDeclaredFields(); //找到全部的属性
for (Field field : fields) {
System.out.println(field);
}
Field name = c1.getDeclaredField("name"); //获得指定属性的值
System.out.println(name);
//获得类的方法
System.out.println("=======================================");
Method[] methods = c1.getMethods(); //获得本类及其父类的全部public方法
for (Method method : methods) {
System.out.println("正常的:"+method);
}
Method[] declaredMethods = c1.getDeclaredMethods(); //获得本类的全部方法
for (Method declaredMethod : declaredMethods) {
System.out.println("declaredMethod: "+declaredMethod);
}
//获得指定方法
Method method = c1.getMethod("getName",null);
Method method1 = c1.getMethod("setName",String.class);
System.out.println(method);
System.out.println(method1);
//获得指定的构造器
System.out.println("=======================================");
Constructor[] constructors = c1.getConstructors();
for (Constructor constructor : constructors) {
System.out.println(constructor);
}
Constructor[] declaredConstructors = c1.getDeclaredConstructors();
for (Constructor declaredConstructor : declaredConstructors) {
System.out.println(declaredConstructor);
}
//获得指定构造器
Constructor declaredConstructor = c1.getDeclaredConstructor(String.class,int.class,int.class);
System.out.println(declaredConstructor);
}
}
有了Class对象,能做什么?
package com.company.reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
//动态创建对象,通过反射
public class Test06 {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
//获得class对象
Class c1 = Class.forName("com.company.reflection.User");
//构造一个对象
User user = (User) c1.newInstance(); //本质是调用了类的无参构造
System.out.println(user);
//通过构造器创建对象
Constructor constructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
User user2 = (User)constructor.newInstance("未激活", 01, 18);
System.out.println(user2);
//通过反射调用普通方法
User user3 = (User) c1.newInstance();
//通过反射获取一个方法
Method setname = c1.getDeclaredMethod("setName", String.class);
//invoke:激活的意思
Object invoke = setname.invoke(user3, "激活成功"); //(对象,"方法的值")
System.out.println(user3.getName());
//通过反射操作属性
System.out.println("===========================");
User user4 = (User) c1.newInstance();
Field name = c1.getDeclaredField("name");
//不能直接操作私有属性,我们需要关闭程序的安全检测,属性或者方法的setAccessible(true)
name.setAccessible(true);
name.set(user2,"激活2");
System.out.println(user2.getName());
}
}
性能对比分析
package com.company.reflection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test07 {
//普通方式调用
public static void test01(){
User user = new User();
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
user.getName();
}
long endTime = System.currentTimeMillis();
System.out.println("普通方式执行10亿次:"+(endTime-startTime)+"ms");
}
//反射方式调用
public static void test02() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user = new User();
Class c1 = user.getClass();
Method getName = c1.getDeclaredMethod("getName", null);
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
getName.invoke(user,null);
}
long endTime = System.currentTimeMillis();
System.out.println("反射方式执行10亿次:"+(endTime-startTime)+"ms");
}
//反射方式调用 关闭检测
public static void test03() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user = new User();
Class c1 = user.getClass();
Method getName = c1.getDeclaredMethod("getName", null);
getName.setAccessible(true);
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
getName.invoke(user,null);
}
long endTime = System.currentTimeMillis();
System.out.println("关闭检测执行10亿次:"+(endTime-startTime)+"ms");
}
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
test01();
test02();
test03();
}
}