注解与反射
注解
package com.kuang.annotation;
import java.util.ArrayList;
/**
* 什么是注解
* @author shiyu
* @date 2021-04-01 15:21
*/
public class Test01 extends Object{
//重写
@Override
public String toString() {
return super.toString();
}
//不推荐使用
@Deprecated
public static void test(){
System.out.println("Deprecated");
}
@SuppressWarnings("all")
public void test02(){
ArrayList arrayList = new ArrayList();
}
public static void main(String[] args) {
test();
}
}
package com.kuang.annotation;
import javax.xml.bind.Element;
import java.lang.annotation.*;
/**
* 测试元注解
* @author shiyu
* @date 2021-04-01 15:34
*/
@MyAnnotation
public class Test02 {
}
//定义一个注解
//Target 表示我们的注解可以用在哪些地方
@Target(value= {ElementType.METHOD,ElementType.TYPE})
//Retention 表示我们的注解在什么地方还有效 注解的生命周期
//runtime > class > sources
@Retention(value = RetentionPolicy.RUNTIME)
//Documented 表示是否将我们的注解生成在javadoc中
@Documented
//Inherited 表示子类可以继承父类的注解
@Inherited
@interface MyAnnotation{
}
package com.kuang.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author shiyu
* @date 2021-04-01 15:53
*/
//自定义注解
public class Test03 {
@MyAnnotation2(age = 18,name = "yuxi")
public void test(){
}
@MyAnnotation3("yuxi")
public void test1(){
}
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
//注解的参数 : 参数类型 + 参数名()
String name() default "";
int age();
int id() default -1;//如果默认值为-1 ,代表不存在。
String[] schools() default {"开源","大学"};
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation3{
String value();
}
反射
package com.kuang.reflection;
/**
* @author shiyu
* @date 2021-04-01 16:21
*/
public class Test01 {
public static void main(String[] args) throws ClassNotFoundException{
//通过反射获取类的class 对象
Class c1 = Class.forName("com.kuang.reflection.User");
System.out.println(c1);
Class c2 = Class.forName("com.kuang.reflection.User");
Class c3 = Class.forName("com.kuang.reflection.User");
Class c4 = Class.forName("com.kuang.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 id;
public User() {
}
public User(String name, int id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
package com.kuang.reflection;
/**
* 测试 class 类的创建方式有哪些
* @author shiyu
* @date 2021-04-01 16:31
*/
public class Test02 {
public static void main(String[] args) throws ClassNotFoundException {
Person p1 = new Student();
System.out.println("这个人是:" + p1.name);
//方式一 : 通过对象获得
Class c1 = p1.getClass();
System.out.println(c1.hashCode());
//方式二 : forName
Class c2 = Class.forName("com.kuang.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.hashCode());
//获得父类类型
Class c5 = c1.getSuperclass();
System.out.println(c5);
}
}
class Person{
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.kuang.reflection;
import java.lang.annotation.ElementType;
/**
* @author shiyu
* @date 2021-04-01 17:06
*/
public class Test03 {
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
int[] a = new int[10];
int[] b = new int[100];
System.out.println(a.getClass().hashCode());
System.out.println(b.getClass().hashCode());
}
}
package com.kuang.reflection;
/**
* @author shiyu
* @date 2021-04-01 17:47
*/
public class Test04 {
public static void main(String[] args) {
A a = new A();
System.out.println(A.m);
/*
1.加载到内存,会产生一个类对应的Class对象
2.链接 ,链接结束后 m=0;
3.初始化
<clinit>(){
System.out.println("A类静态代码块初始化");
m = 300;
m = 100;
}
m = 100;
*/
}
}
class A{
static {
System.out.println("A类静态代码块初始化");
m = 300;
}
static int m = 100;
public A(){
System.out.println("A类无参构造初始化");
}
}
package com.kuang.reflection;
/**
* 测试类初始化
* @author shiyu
* @date 2021-04-01 18:28
*/
public class Test05 {
static{
System.out.println("Main类被加载");
}
public static void main(String[] args) throws ClassNotFoundException {
//1.主动引用
//Son son = new Son();
//反射也会产生主动引用
//Class.forName(("com.kuang.reflection.son"));
//不会产生类的引用的方法
//System.out.println(Son.b); 类的静态变量
//Son[] arr = new Son[5]; 常量
System.out.println(Son.M);
}
}
class Father{
static int b = 2;
static{
System.out.println("父类被加载");
}
}
class Son extends Father{
static {
System.out.println("子类被加载");
m = 300;
}
static int m = 100;
static final int M = 1;
}
package com.kuang.reflection;
/**
* @author shiyu
* @date 2021-04-01 18:50
*/
public class Test07 {
public static void main(String[] args) throws ClassNotFoundException {
//获取系统类的加载器
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
System.out.println(systemClassLoader);
//获取系统类的加载器的父类加载器 -->扩展类加载器
ClassLoader parent = systemClassLoader.getParent();
System.out.println(parent);
//获取扩展类加载器的父类加载器 ---> 根加载器(引导类加载器)
ClassLoader parent1 = parent.getParent();
System.out.println(parent1);
//测试当前类是哪个加载器加载的
ClassLoader aClass = Class.forName("com.kuang.reflection.Test07").getClassLoader();
System.out.println(aClass);
//测试JDK 内置的类的加载器
ClassLoader aL = Class.forName("java.lang.Object").getClassLoader();
System.out.println(aL);
//如何获得系统类加载器可以加载的路径
System.out.println(System.getProperty("java.class.path"));
}
}
package com.kuang.reflection;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* //获取类的信息
* @author shiyu
* @date 2021-04-01 19:07
*/
public class Test08 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
Class c1 = Class.forName("com.kuang.reflection.User");
//获得类的名字
System.out.println(c1.getName());//包名 + 类名
System.out.println(c1.getSimpleName());//类名
//获得类的属性
System.out.println("===============================");
Field[] fields = c1.getFields();//只能找到public属性
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);
}
methods = c1.getDeclaredMethods();//获得本类所有方法
for (Method method : methods){
System.out.println("getDeclaredMethods" + method);
}
//获得指定的构造器
//重载
System.out.println("=======================");
Method getName = c1.getMethod("getName", null);
Method setName = c1.getMethod("setName", String.class);
System.out.println(getName);
System.out.println(setName);
//获得指定的构造器
System.out.println("============================");
Constructor[] constructors = c1.getConstructors();
for (Constructor constructor : constructors){
System.out.println(constructor);
}
constructors = c1.getDeclaredConstructors();
for (Constructor constructor : constructors){
System.out.println(constructor);
}
//获得指定的构造器
Constructor declaredConstructor = c1.getDeclaredConstructor(String.class,int.class);
System.out.println("指定的" + declaredConstructor);
}
}
package com.kuang.reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* 动态的创建对象,通过反射
* @author shiyu
* @date 2021-04-01 19:35
*/
public class Test09 {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
//获得Class对象
Class c1 = Class.forName("com.kuang.reflection.User");
//构造一个对象
// User user = (User)c1.newInstance();//本质调用类的无参构造器
// System.out.println(user);
//通过构造器创建对象
// Constructor constructor = c1.getDeclaredConstructor(String.class, int.class);
// User user2 = (User)constructor.newInstance("yuxi",123);
// System.out.println(user2);
//通过反射调用普通方法
User user3 = (User)c1.newInstance();
//通过反射获取一个普通方法
Method setName = c1.getDeclaredMethod("setName", String.class);
//invoke : 激活
//(对象 , "方法的值")
setName.invoke(user3,"hello");
System.out.println(user3.getName());
//通过反射操作属性
User user4 = (User)c1.newInstance();
Field name = c1.getDeclaredField("name");
//不能直接操作私有属性,我们需要关闭程序的安全检测,属性或者方法的setAccessible(true)
name.setAccessible(true);
name.set(user4,"haha");
System.out.println(user4.getName());
}
}
package com.kuang.reflection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* 分析性能问题
* @author shiyu
* @date 2021-04-01 20:04
*/
public class Test10 {
//普通方式
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("普通方式执行一亿次 : " + (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("反射方式执行一亿次 : " + (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("关闭检测方式执行一亿次 : " + (endTime - startTime) + "ms");
}
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
test01();
test02();
test03();
}
}
package com.kuang.reflection;
import java.lang.annotation.*;
import java.lang.reflect.Field;
/**
* 反射操作注解
* @author shiyu
* @date 2021-04-01 20:23
*/
public class Test11 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class c1 = Class.forName("com.kuang.reflection.Student1");
//通过反射获得注解
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
//获得注解value的值
TableY tableY = (TableY)c1.getAnnotation(TableY.class);
String value = tableY.value();
System.out.println(value);
//获得类指定的注解
Field f = c1.getDeclaredField("name");
FieldX annotation = f.getAnnotation(FieldX.class);
System.out.println(annotation.columnName());
System.out.println(annotation.type());
System.out.println(annotation.length());
}
}
@TableY("db_student")
class Student1{
@FieldX(columnName = "db_id",type = "int",length = 10)
private int id;
@FieldX(columnName = "db_name",type = "varchar",length = 10)
private String name;
@FieldX(columnName = "db_age",type = "int",length = 10)
private int age;
public Student1() {
}
public Student1(String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
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;
}
@Override
public String toString() {
return "Student1{" +
"name='" + name + '\'' +
", id=" + id +
", age=" + age +
'}';
}
}
//类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableY{
String value();
}
//属性注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldX{
String columnName();
String type();
int length();
}
(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student1{" +
"name='" + name + '\'' +
", id=" + id +
", age=" + age +
'}';
}
}
//类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableY{
String value();
}
//属性注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldX{
String columnName();
String type();
int length();
}