【Java】注解与反射(三)——创建运行时类的对象
✨获取类的运行时结构
package com.example.reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
//获取类的运行时结构
public class Test07 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
Class<?> c1 = Class.forName("com.example.reflection.User");
// 获得类的名字
System.out.println(c1.getName());
System.out.println(c1.getSimpleName());
User user = new User();
Class<? extends User> c2 = user.getClass();
System.out.println(c2.getName());
System.out.println(c2.getSimpleName());
// 获得类的属性
System.out.println("==============================");
// 只能找到public属性
Field[] fields = c1.getFields();
for (Field field : fields) {
System.out.println(field);
}
System.out.println("==============================");
// 能找到全部属性
Field[] declaredFields = c1.getDeclaredFields();
for (Field declaredField : declaredFields) {
System.out.println(declaredField);
}
// 获取指定属性
System.out.println("==============================");
Field name = c1.getDeclaredField("name");
System.out.println(name);
// 获得类的方法
System.out.println("==============================");
// 获得本类及其父类的全部public方法
Method[] methods = c1.getMethods();
System.out.println("-----");
for (Method method : methods) {
System.out.println("[getMethods()]" + method);
}
// 获得本类的所有方法
Method[] declaredMethods = c1.getDeclaredMethods();
System.out.println("-----");
for (Method declaredMethod : declaredMethods) {
System.out.println("[getDeclaredMethods()]" + declaredMethod);
}
// 获得指定方法
// 根据parameterTypes获得不同的方法(重载)
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("==============================");
// 获得public构造器
Constructor<?>[] constructors = c1.getConstructors();
// 获得全部构造器
Constructor<?>[] declaredConstructors = c1.getDeclaredConstructors();
for (Constructor<?> constructor : constructors) {
System.out.println("[getConstructors()]" + constructor);
}
for (Constructor<?> declaredConstructor : declaredConstructors) {
System.out.println("[declaredConstructor()]"+ declaredConstructor);
}
// 获得指定构造器
System.out.println("-----");
Constructor<?> constructor = c1.getConstructor(null);
System.out.println(constructor);
}
}
✨动态创建对象执行方法
package com.example.reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
//动态创建对象执行方法
public class Test08 {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
// 获得Class对象
Class<?> c1 = Class.forName("com.example.reflection.User");
// 构造对象
// 调用了无参构造器
User user = (User) c1.newInstance();
System.out.println(user);
// 通过构造器创建对象
Constructor<?> constructor = c1.getDeclaredConstructor(int.class, String.class, int.class);
User user2 = (User) constructor.newInstance(1, "username", 66);
System.out.println(user2);
// 通过反射调用方法
User user3 = (User) c1.newInstance();
// 通过反射获取一个方法
Method setName = c1.getMethod("setName", String.class);
// invoke 激活(调用)
// (对象实例,参数)
setName.invoke(user3, "通过反射调用方法");
System.out.println(user3.getName());
// 通过反射操作属性
User user4 = (User) c1.newInstance();
Field name = c1.getDeclaredField("name");
// 不能直接操作private属性 需要关闭检测
// 属性/方法.setAccessible(true)
name.setAccessible(true);
name.set(user4, "通过反射操作属性");
System.out.println(user4.getName());
}
}
✨性能分析对比
package com.example.reflection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
//性能分析对比
public class Test09 {
// 普通方式调用
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("[普通方式调用10亿次]" + (endTime - startTime) + "ms");
}
// 反射方式调用
public static void test02() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user = new User();
Class<? extends User> c1 = user.getClass();
Method getName = c1.getMethod("getName", null);
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
getName.invoke(user, null);
}
long endTime = System.currentTimeMillis();
System.out.println("[反射方式调用10亿次]" + (endTime - startTime) + "ms");
}
// 反射方式调用(关闭检测)
public static void test03() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user = new User();
Class<? extends User> c1 = user.getClass();
Method getName = c1.getMethod("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("[反射方式调用(关闭检测)10亿次]" + (endTime - startTime) + "ms");
}
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
test01();
test02();
test03();
// [普通方式调用10亿次]6ms
// [反射方式调用10亿次]6879ms
// [反射方式调用(关闭检测)10亿次]2122ms
}
}
✨获取泛型信息
package com.example.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 Test10 {
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 method = Test10.class.getMethod("test01", Map.class, List.class);
Type[] genericParameterTypes = method.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 = Test10.class.getMethod("test02", null);
Type genericReturnType = method.getGenericReturnType();
if(genericReturnType instanceof ParameterizedType){
Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println(actualTypeArgument);
}
}
}
}
✨获取注解信息
package com.example.reflection;
import java.lang.annotation.*;
import java.lang.reflect.Field;
//获取注解信息
public class Test11 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class<?> c1 = Class.forName("com.example.reflection.Student2");
// 通过反射获得注解
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
// 获得注解value的值
TableAnnotation tableAnnotation = c1.getAnnotation(TableAnnotation.class);
System.out.println(tableAnnotation.value());
// 获得类指定的的注解
Field name = c1.getDeclaredField("name");
FieldAnnotation nameAnnotation = name.getAnnotation(FieldAnnotation.class);
System.out.println(nameAnnotation.columnName());
System.out.println(nameAnnotation.type());
System.out.println(nameAnnotation.length());
}
}
@TableAnnotation("db_student")
class Student2{
@FieldAnnotation(columnName = "db_id", type = "int", length = 10)
private int id;
@FieldAnnotation(columnName = "db_age", type = "int", length = 10)
private int age;
@FieldAnnotation(columnName = "db_name", type = "varchar", length = 10)
private String name;
public Student2() {
}
public Student2(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 "Student2{" +
"id=" + id +
", age=" + age +
", name='" + name + '\'' +
'}';
}
}
//类名注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableAnnotation{
String value();
}
//属性注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldAnnotation{
String columnName();
String type();
int length();
}
✨课程链接
⭐转载请注明出处
本文作者:双份浓缩馥芮白
原文链接:https://www.cnblogs.com/Flat-White/p/15168719.html
版权所有,如需转载请注明出处。