第十六话-Java注解和反射
什么是注解

内置注解

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();
}
以上仅供参考,如有疑问,留言联系

浙公网安备 33010602011771号