Skip to content

Commit

Permalink
Replace "google.common.reflect.* TypeToken" API with jdk API (alibaba…
Browse files Browse the repository at this point in the history
…#6527)

* Replace "google.common.reflect.* TypeToken" API with jdk API

* update unit test
  • Loading branch information
ZZQ001010 authored Aug 4, 2021
1 parent 787e161 commit 995cd7a
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 7 deletions.
29 changes: 27 additions & 2 deletions core/src/main/java/com/alibaba/nacos/core/utils/GenericType.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,40 @@

package com.alibaba.nacos.core.utils;

import com.google.common.reflect.TypeToken;
import com.alibaba.nacos.common.utils.Preconditions;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;

/**
* Encapsulates third party tools for generics acquisition.
*
* @author <a href="mailto:[email protected]">liaochuntao</a>
*/
public class GenericType<T> extends TypeToken<T> {
public class GenericType<T> {

private static final long serialVersionUID = -2103808581228167629L;

private final Type runtimeType;

final Type capture() {
Type superclass = getClass().getGenericSuperclass();
Preconditions.checkArgument(superclass instanceof ParameterizedType, "%s isn't parameterized", superclass);
return ((ParameterizedType) superclass).getActualTypeArguments()[0];
}

protected GenericType() {
this.runtimeType = capture();
if (runtimeType instanceof TypeVariable) {
throw new IllegalArgumentException("runtimeType must be ParameterizedType Class");
}
}

/**
* Returns the represented type.
*/
public final Type getType() {
return runtimeType;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@

package com.alibaba.nacos.core.utils;

import com.google.common.reflect.TypeToken;
import org.junit.Assert;
import org.junit.Test;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

/**
Expand All @@ -30,10 +31,10 @@ public class ClassUtilsTest {

@Test
public void testGeneric() {
GenericType<List<String>> genericType = new GenericType<List<String>>() {
};
Assert.assertEquals(genericType.getType(), new TypeToken<java.util.List<java.lang.String>>() {
}.getType());
Type type = new GenericType<List<String>>() {
}.getType();
Assert.assertEquals("java.util.List<java.lang.String>", type.getTypeName());
Assert.assertTrue(type instanceof ParameterizedType);
}

@Test
Expand Down

0 comments on commit 995cd7a

Please sign in to comment.