反射会使性能变慢
使用反射读取注解的信息,模拟处理注解的过程
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
/**
* 使用反射读取注解的信息,模拟处理注解的过程
*/
public class Demo01 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class aClass=Class.forName("com.annotation.Student");
//获取类的所有有效注解
Annotation[] annntations=aClass.getAnnotations();
for (Annotation a:annntations
) {
System.out.println(a);
}
//获取指定的注解
Table table=(Table)aClass.getAnnotation(Table.class);
System.out.println(table.value());
//获取类的属性注解
Field field=aClass.getDeclaredField("name");
TableField tableField=field.getAnnotation(TableField.class);
System.out.printf(tableField.columnName()+" --"+tableField.type()+"--"+tableField.length());
}
}
package com.annotation;
@Table(value = "tb_student")
public class Student {
@TableField(columnName = "id",type = "int",length = 10)
private int id;
@TableField(columnName = "name",type = "varchar",length = 10)
private String name;
@TableField(columnName = "age",type = "int",length = 3)
private int age;
public Student() {
}
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
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;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
package com.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
String value();
}
package com.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TableField {
String columnName();
String type();
int length();
}
通过反射API调用构造方法、构造对象
通过API调用普通方法
通过反射API操作属性
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
*通过反射API调用构造方法、构造对象
* 通过API调用普通方法
* 通过反射API操作属性
*/
public class Demo03 {
public static void main(String[] args) {
String path="com.annotation.Student";
Class aClass;
{
try {
aClass = Class.forName(path);
//通过反射API调用构造方法、构造对象
Student student=(Student)aClass.newInstance();//调用无参构造方法
System.out.println(student);
Constructor<Student> c=aClass.getConstructor(int.class,String.class,int.class);
Student student1=c.newInstance(1001,"zhang",21);
System.out.println(student1.getName());
//通过API调用普通方法
Student student2=(Student)aClass.newInstance();
Method method=aClass.getMethod("setName",String.class);
method.invoke(student2,"zhang2");
System.out.println(student2.getName());
//通过反射API操作属性
Student student3=(Student)aClass.newInstance();
Field field=aClass.getDeclaredField("name");
field.setAccessible(true);//调用private属性
field.set(student3,"zhang3");
System.out.println(student3.getName());
System.out.println(field.get(student3));//通过反射直接读取
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
}
}
setAccessible
为true时,禁止访问检查,使反射效率大大提高
反射调用效率低,将setAccessible设为true使效率相对提高
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test {
public void start(){
Student student=new Student();
long startTime=System.currentTimeMillis();
for(long i=0;i<1000000000L;i++){
student.getName();
}
long endTime=System.currentTimeMillis();
System.out.println("耗时:"+(endTime-startTime));
}
public void start2() throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
Student student2=new Student();
Class c=student2.getClass();
Method method=c.getMethod("getName",null);
long startTime=System.currentTimeMillis();
for(long i=0;i<1000000000L;i++){
method.invoke(student2,null);
}
long endTime=System.currentTimeMillis();
System.out.println("耗时:"+(endTime-startTime));
}
public void start3() throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Student student3=new Student();
Class c=student3.getClass();
Method method=c.getMethod("getName",null);
method.setAccessible(true);//不执行安全检查
long startTime=System.currentTimeMillis();
for(long i=0;i<1000000000L;i++){
method.invoke(student3,null);
}
long endTime=System.currentTimeMillis();
System.out.println("耗时:"+(endTime-startTime));
}
public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
Test t=new Test();
t.start();
t.start2();
t.start3();
}
}
反射操作泛型
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.*;
public class Demo04 {
public void test01(Map<String,String> map, List<Student> list){
}
public List<Student> test02(){
return new ArrayList<>();
}
public static void main(String[] args) throws NoSuchMethodException {
Method m=Demo04.class.getDeclaredMethod("test01", Map.class, List.class);
Type[] types=m.getGenericParameterTypes();
for (Type t:types
) {
System.out.println("*"+t);
if(t instanceof ParameterizedType){
Type[] generictypes=((ParameterizedType)t).getActualTypeArguments();
for (Type t2:generictypes
) {
System.out.println(t2);
}
}
}
Method m2=Demo04.class.getMethod("test02",null);
Type types1=m2.getGenericReturnType();
System.out.println("*"+types1);
if(types1 instanceof ParameterizedType){
Type[] types2=((ParameterizedType)types1).getActualTypeArguments();
for (Type temp:types2
) {
System.out.println(temp);
}
}
}
}