ResolvableType 中的方法使用案例
时间: 2024-05-03 22:22:29 浏览: 120
Spring 中优雅的获取泛型信息的方法
1. 获取泛型类型
```java
public class UserList extends ArrayList<User> {}
// 使用 ResolvableType 获取 UserList 类的泛型类型
ResolvableType resolvableType = ResolvableType.forClass(UserList.class);
ResolvableType genericType = resolvableType.getGeneric(0);
System.out.println(genericType.getType()); // class com.example.User
```
2. 获取父类泛型类型
```java
public abstract class BaseService<T> {}
public class UserService extends BaseService<User> {}
// 使用 ResolvableType 获取 UserService 类的父类泛型类型
ResolvableType resolvableType = ResolvableType.forClass(UserService.class);
ResolvableType genericType = resolvableType.getSuperType().getGeneric(0);
System.out.println(genericType.getType()); // class com.example.User
```
3. 获取字段的泛型类型
```java
public class UserResponse<T> {
private T data;
}
public class User {
private UserResponse<String> response;
}
// 使用 ResolvableType 获取 User 类的 response 字段的泛型类型
Field field = User.class.getDeclaredField("response");
ResolvableType resolvableType = ResolvableType.forField(field);
ResolvableType genericType = resolvableType.getGeneric(0);
System.out.println(genericType.getType()); // class java.lang.String
```
4. 获取方法的泛型类型
```java
public interface BaseService<T> {
T get();
}
public class UserService implements BaseService<User> {
@Override
public User get() {
return null;
}
}
// 使用 ResolvableType 获取 UserService 类实现的 get 方法的泛型类型
Method method = UserService.class.getMethod("get");
ResolvableType resolvableType = ResolvableType.forMethodReturnType(method);
ResolvableType genericType = resolvableType.getGeneric(0);
System.out.println(genericType.getType()); // class com.example.User
```
阅读全文