第十六話-Java註解和反射
阿新 • • 發佈:2022-05-08
什麼是註解
內建註解
package com.xie.annotation; import java.util.ArrayList; import java.util.List; @SuppressWarnings("all") public class Test01 { @Deprecated public static void test(){ System.out.println("Deprecated"); } public void test2(){ List list = new ArrayList<String >(); } public static void main(String[] args) { test(); } }
元註解
自定義註解
package com.xie.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; public class Test2 { @MyAnnotation(age = 18,name = "xiexieyc") @MyAnnotation2("ceshi") public void test(){} } @Target({ElementType.TYPE,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @interface MyAnnotation{ //註解的引數: 引數型別 + 引數名() String name() default ""; int age(); int id() default -1; //如果預設值為-1,則代表不存在 String[] schools() default {"清華大學","西電"}; } @Target({ElementType.TYPE,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @interface MyAnnotation2{ String value(); }
反射概述
動態語言和靜態語言
反射定義
反射機制提供的功能
反射優缺點
獲得反射物件
反射相關的主要API
package com.xie.reflection; public class Test1 { public static void main(String[] args) throws ClassNotFoundException { //通過反射獲取類的Class物件 Class c1 = Class.forName("com.xie.reflection.User"); System.out.println(c1); Class c2 = Class.forName("com.xie.reflection.User"); Class c3 = Class.forName("com.xie.reflection.User"); Class c4 = Class.forName("com.xie.reflection.User"); //一個類在記憶體中只有一個Class物件 //一個類被載入後,類的整個結構都會被封裝在Class物件中 System.out.println(c2.hashCode()); System.out.println(c3.hashCode()); System.out.println(c4.hashCode()); } } //實體類: pojo、entity class User{ String name; int age; 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類的幾種方式
Class類
Class類的常用方法
獲得class類的例項
package com.xie.reflection;
public class Test03 {
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.xie.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 = "老師";
}
}
哪些型別可以有Class物件
獲取類的執行時結構
package com.xie.reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Test08 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
Class c1 = Class.forName("com.xie.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("public修飾的方法:"+method);
}
methods = c1.getDeclaredMethods();//本類的所有方法
for (Method method : methods) {
System.out.println("本類的方法:"+method);
}
//獲得指定方法
Method getName = c1.getMethod("getName",null);
Method setName = c1.getMethod("setName", String.class);
System.out.println(getName);
System.out.println(setName);
//獲得構造器
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, int.class);
System.out.println(declaredConstructor);
}
}
動態建立物件執行方法
package com.xie.reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test09 {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
//獲得Class物件
Class c1 = Class.forName("com.xie.reflection.User");
//構造一個物件
User user = (User) c1.newInstance();
System.out.println(user);
//通過構造器建立物件
Constructor constructor = c1.getDeclaredConstructor(String.class,int.class,int.class);
user = (User)constructor.newInstance("xie",11,12);
System.out.println(user);
//通過反射呼叫普通方法
Method setName = c1.getDeclaredMethod("setName", String.class);
//invoke:啟用(物件,方法的引數值)
setName.invoke(user,"xie2");
System.out.println(user);
//通過反射操作屬性
System.out.println("===================");
Field name = c1.getDeclaredField("name");
//不能直接操作私有屬性,需要先關閉程式的安全檢測,屬性或方法的setAccessible(true)
name.setAccessible(true);
name.set(user,"xie3");
System.out.println(user);
}
}
效能對比
package com.xie.reflection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
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 InvocationTargetException, NoSuchMethodException, IllegalAccessException {
test01();
test02();
test03();
}
}
獲取泛型資訊
package com.xie.reflection;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
public class Test11 {
public void test01(Map<String ,User> map, List<User> list){
System.out.println("test01");
}
public Map<String,User> test02(){
System.out.println("test02");
return null;
}
public static void main(String[] args) throws NoSuchMethodException {
Method test01 = Test11.class.getDeclaredMethod("test01", Map.class, List.class);
Type[] genericParameterTypes = test01.getGenericParameterTypes();
for (Type genericParameterType : genericParameterTypes) {
System.out.println("#"+genericParameterType);
if(genericParameterType instanceof ParameterizedType){
Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println(actualTypeArgument);
}
}
}
System.out.println("==============");
Method test02 = Test11.class.getDeclaredMethod("test02", null);
Type genericReturnType = test02.getGenericReturnType();
System.out.println(genericReturnType);
if(genericReturnType instanceof ParameterizedType){
Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println(actualTypeArgument);
}
}
}
}
獲取註解資訊
package com.xie.reflection;
import java.lang.annotation.*;
import java.lang.reflect.Field;
public class Test12 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class c1 = Class.forName("com.xie.reflection.Student2");
//通過反射獲取註解
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
//獲得註解的value值
TableXie tableXie = (TableXie) c1.getAnnotation(TableXie.class);
String value = tableXie.value();
System.out.println(value);
//獲得類指定的註解
Field name = c1.getDeclaredField("name");
FieldXie annotation = name.getAnnotation(FieldXie.class);
System.out.println(annotation.columnName());
System.out.println(annotation.type());
System.out.println(annotation.length());
}
}
@TableXie("db_student")
class Student2{
@FieldXie(columnName = "db_id",type = "int",length = 10)
private int id;
@FieldXie(columnName = "db_name",type = "varchar",length = 255)
private String name;
public Student2() {
}
public Student2(int id, String name) {
this.id = id;
this.name = name;
}
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;
}
@Override
public String toString() {
return "Student2{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
//類名的註解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableXie{
String value();
}
//屬性的註解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldXie{
String columnName();
String type();
int length();
}