!1092 TypeUtil.getClass方法强转报错问题

Merge pull request !1092 from flavormark/v5-dev
This commit is contained in:
Looly 2023-10-12 13:27:36 +00:00 committed by Gitee
commit 8df5997165
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
2 changed files with 39 additions and 19 deletions

View File

@ -40,7 +40,10 @@ public class TypeUtil {
} else if (type instanceof ParameterizedType) {
return (Class<?>) ((ParameterizedType) type).getRawType();
} else if (type instanceof TypeVariable) {
return (Class<?>) ((TypeVariable<?>) type).getBounds()[0];
Type[] bounds = ((TypeVariable<?>) type).getBounds();
if (bounds.length == 1) {
return getClass(bounds[0]);
}
} else if (type instanceof WildcardType) {
final Type[] upperBounds = ((WildcardType) type).getUpperBounds();
if (upperBounds.length == 1) {

View File

@ -1,13 +1,12 @@
package cn.hutool.core.util;
import lombok.Data;
import org.junit.Assert;
import org.junit.Test;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
import org.junit.Assert;
import org.junit.Test;
public class TypeUtilTest {
@ -31,18 +30,32 @@ public class TypeUtilTest {
Assert.assertEquals(Integer.class, returnType);
}
@Test
public void getClasses() {
Method method = ReflectUtil.getMethod(Parent.class, "getLevel");
Type returnType = TypeUtil.getReturnType(method);
Class clazz = TypeUtil.getClass(returnType);
Assert.assertEquals(Level1.class, clazz);
method = ReflectUtil.getMethod(Level1.class, "getId");
returnType = TypeUtil.getReturnType(method);
clazz = TypeUtil.getClass(returnType);
Assert.assertEquals(Object.class, clazz);
}
public static class TestClass {
public List<String> getList(){
public List<String> getList() {
return new ArrayList<>();
}
public Integer intTest(Integer integer) {
return 1;
}
}
@Test
public void getTypeArgumentTest(){
public void getTypeArgumentTest() {
// 测试不继承父类而是实现泛型接口时是否可以获取成功
final Type typeArgument = TypeUtil.getTypeArgument(IPService.class);
Assert.assertEquals(String.class, typeArgument);
@ -59,25 +72,29 @@ public class TypeUtilTest {
}
@Test
public void getActualTypesTest(){
public void getActualTypesTest() {
// 测试多层级泛型参数是否能获取成功
Type idType = TypeUtil.getActualType(Level3.class,
ReflectUtil.getField(Level3.class, "id"));
Type idType = TypeUtil.getActualType(Level3.class, ReflectUtil.getField(Level3.class, "id"));
Assert.assertEquals(Long.class, idType);
}
public static class Level3 extends Level2<Level3>{
public static class Level3 extends Level2<Level3> {
}
public static class Level2<E> extends Level1<Long>{
public static class Level2<E> extends Level1<Long> {
}
@Data
public static class Level1<T>{
public static class Level1<T> {
private T id;
}
@Data
public static class Parent<T extends Level1<B>, B extends Long> {
private T level;
}
}