Java反射的常用方法

java.lang.Class

getTypeParameters

public class ClassTest {

	public static class ClassTest0 {}
	public static class ClassTest1<T> {}
	
	@Test
	public void test_getTypeParameters() {
		assertEquals(2, Map.class.getTypeParameters().length);
		assertEquals("E", Map.class.getTypeParameters()[0].getName());
		assertEquals("F", Map.class.getTypeParameters()[1].getName());
		
		assertEquals(0, ClassTest0.class.getTypeParameters().length);
		assertEquals("T", ClassTest1.class.getTypeParameters()[0].getName());
	}
}

java.lang.reflect.Method

getDeclaringClass

public class MethodTest {
	static class Foo {
		void getOne() { }
		String getTwo() { return "two"; }
	}
	
	@Test
	public void testGetDeclaringClass() {
		for (Method m : Foo.class.getDeclaredMethods()) {
			assertEquals(Foo.class, m.getDeclaringClass());
		}
	}
}

getParameterTypes

	static class Foo2 {
		int getOne(String s, Number n) { return 0; }
	}
	
	@Test
	public void testGetParameterTypes() {
		Method m = Foo2.class.getDeclaredMethods()[0];
		Class<?>[] pts = m.getParameterTypes();
		assertEquals(String.class, pts[0]);
		assertEquals(Number.class, pts[1]);
	}

getGenericReturnType与getReturnType

	static class Foo3<T> {
		T getOne() { return null; }
	}
	
	@Test
	public void testGetGenericReturnType() {
		Method m = Foo3.class.getDeclaredMethods()[0];
		assertEquals(Object.class, m.getReturnType());
		assertTrue(m.getGenericReturnType() instanceof TypeVariable);
		assertEquals("T", ((TypeVariable)m.getGenericReturnType()).getName());
	}
	
	
	static class Foo4<T> {
		List<T> getOne() { return null; }
	}
	
	@Test
	public void testGetGenericReturnType2() {
		Method m = Foo4.class.getDeclaredMethods()[0];
		assertEquals(List.class, m.getReturnType());
		assertTrue(m.getGenericReturnType() instanceof ParameterizedType);
		ParameterizedType parameterizedType = (ParameterizedType)m.getGenericReturnType();
		Type subType = parameterizedType.getActualTypeArguments()[0];
		assertTrue(subType instanceof TypeVariable);
                assertEquals("T", ((TypeVariable)subType).getName());
	}
posted @ 2020-11-25 12:04  ralgo  阅读(281)  评论(0)    收藏  举报