分割线

操作 Class 对象

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Demo6 {

public static void main(String[] args) throws Exception {
//获得class对象
Class c1 = User.class;

//创建一个对象
User user = (User) c1.newInstance();//本质是调用了类的无参构造器
System.out.println(user);

//通过构造器创建对象
System.out.println("============================");
Constructor constructor = c1.getDeclaredConstructor(String.class, int.class);
User user2 = (User) constructor.newInstance("打爆", 22);
System.out.println(user2);

//通过反射获取一个方法
System.out.println("============================");
Method setName = c1.getDeclaredMethod("setName", String.class);
/**
* invoke: 激活
* invoke(执行方法的对象+原方法的参数1+原方法的参数2+...)
*/
setName.invoke(user, "Weidows");
System.out.println(user.getName());

//通过反射操作属性
System.out.println("============================");
User user3 = (User) c1.newInstance();
Field name = c1.getDeclaredField("name");
//不能直接操作私有属性,我们需要关闭程序的安全监测,属性或方法的setAccessible(true)
name.setAccessible(true);
name.set(user3, "齐下无贰");
System.out.println(user3.getName());

/**
twenty_one.reflection.User@59f95c5d
============================
twenty_one.reflection.User@5c8da962
============================
Weidows
============================
齐下无贰
*/
}
}

class User {
private String name;
private int age;

public User() {
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public User(String name, int age) {
this.name = name;
this.age = age;
}
}

分割线

性能分析

import java.lang.reflect.Method;

public class PerformanceInfluence {

public static void main(String[] args) throws Exception {
test1();
test2();
test3();
/**
普通方式执行4ms
反射方式,开启检测执行2794ms
反射方式,关闭检测执行1771ms
*/
}

public static void test1() {
User user = new User();
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
user.getName();
}
long end = System.currentTimeMillis();
System.out.println("普通方式执行" + (end - start) + "ms");
}

public static void test2() throws Exception {
User user = new User();
Class c1 = user.getClass();
Method getName = c1.getDeclaredMethod("getName", null);

long start = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
getName.invoke(user, null);
}
long end = System.currentTimeMillis();
System.out.println("反射方式,开启检测执行" + (end - start) + "ms");
}

public static void test3() throws Exception {
User user = new User();
Class c1 = user.getClass();
Method getName = c1.getDeclaredMethod("getName", null);

long start = System.currentTimeMillis();
getName.setAccessible(true);
for (int i = 0; i < 1000000000; i++) {
getName.invoke(user, null);
}
long end = System.currentTimeMillis();
System.out.println("反射方式,关闭检测执行" + (end - start) + "ms");
}
}
  • 可见使用反射方式执行效率远远远远低于正常执行,关闭访问权限检测也只能降低部分性能损耗

分割线

反射操作泛型

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 Generic {

public void test01(Map<String, User> map, List<User> list) {
}

public Map<String, User> test02() {
return null;
}

public static void main(String[] args) throws NoSuchMethodException {
/**
* 获取参数(map,list)的泛型参数(String,User)
*/
Method method = Generic.class.getMethod("test01", Map.class, List.class);
Type[] genericParameterTypes = method.getGenericParameterTypes();
for (Type genericParameterType : genericParameterTypes) {
System.out.println("范型参数" + genericParameterType);
if (genericParameterType instanceof ParameterizedType) {
Type[] actualTypeAnguments = ((ParameterizedType) genericParameterType).getActualTypeArguments();
for (Type actualTypeAngument : actualTypeAnguments) {
System.out.println(" 实际参数范型" + actualTypeAngument);
}
}
}

System.out.println("--------------------------------------------");

/**
* 获取返回值的泛型参数
*/
Method method1 = Generic.class.getMethod("test02", null);
Type getGenericReturnType = method1.getGenericReturnType();
if (getGenericReturnType instanceof ParameterizedType) {
Type[] actualTypeArguments = ((ParameterizedType) getGenericReturnType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println("返回值范型" + actualTypeArgument);
}
}
}
/**
范型参数java.util.Map<java.lang.String, twenty_one.reflection.User>
实际参数范型class java.lang.String
实际参数范型class twenty_one.reflection.User
范型参数java.util.List<twenty_one.reflection.User>
实际参数范型class twenty_one.reflection.User
--------------------------------------------
返回值范型class java.lang.String
返回值范型class twenty_one.reflection.User
*/
}

分割线

反射操作注解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

public class Annotation {
public static void main(String[] args) throws NoSuchFieldException, SecurityException {
// * 通过反射获取注解
java.lang.annotation.Annotation[] annotations = Student1.class.getAnnotations();
for (java.lang.annotation.Annotation annotation : annotations) {
System.out.println(annotation);
}

// * 获取注解的value
Table annotation = Student1.class.getAnnotation(Table.class); //获取Student1类上Table类型的注解
System.out.println(annotation.value());

// * 获取指定的value
java.lang.reflect.Field f = Student1.class.getDeclaredField("name");
Field annotation1 = f.getAnnotation(Field.class);
System.out.println(annotation1.columnName() + "\t" + annotation1.type() + "\t" + annotation1.length());
}
/**
@twenty_one.reflection.Table(value="db_student")
db_student
db_name varchar 3
*/
}

@Table(value = "db_student")
class Student1 {
@Field(columnName = "db_id", type = "int", length = 10)
private int id;
@Field(columnName = "db_age", type = "int", length = 10)
private int age;
@Field(columnName = "db_name", type = "varchar", length = 3)
private String name;

public Student1() {
}

public Student1(int id, int age, String name) {
this.id = id;
this.age = age;
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;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "Student [age=" + age + ", id=" + id + ", name=" + name + "]";
}
}

// ! 类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Table {
String value();
}

// ! 属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Field {
String columnName();

String type();

int length();
}