Java SE: Reflection Introduction (RTTI)

1. Get Class object (Three possible ways)

        1) Using Class.forName(className). The static method of Class class

package edu.xmu.service;

import org.junit.Test;

public class UserServiceTest
{

	@Test
	public void test()
	{
		try
		{
			Class<?> userServiceClazz = Class.forName("edu.xmu.service.UserService");
			
			System.out.println(userServiceClazz.getName());
		} catch (ClassNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

         2) Fetch the Class reference by calling a method that's part of the Object root class: getClass()

package edu.xmu.service;

import org.junit.Test;

public class UserServiceTest
{
	@Test
	public void test()
	{
		UserService userService = new UserService();
		Class<?> userServiceClazz = userService.getClass();
		System.out.println(userServiceClazz.getName());
	}
}

         3) Using class literals

package edu.xmu.service;

import org.junit.Test;

public class UserServiceTest
{
	@Test
	public void test()
	{
		Class<?> userServiceClazz = UserService.class;
		System.out.println(userServiceClazz.getName());
	}
}

 

2. Instantiate Object Using Constructor (Two possible approaches)

        1) Using newInstance() method in Class object for non-param constructor

package edu.xmu.service;

import org.junit.Test;

public class UserServiceTest
{
	@Test
	public void test() throws InstantiationException, IllegalAccessException
	{
		Class<?> userServiceClazz = UserService.class;
		UserService userService = (UserService) userServiceClazz.newInstance();
		userService.addUser();
	}
}

         2) Using getConstructor(paramClasses) in Class object. Then use newInstance(paramValues) in Constructor instance.

package edu.xmu.service;

import java.lang.reflect.Constructor;

import org.junit.Test;

public class UserServiceTest
{
	@Test
	public void test() throws Exception
	{
		Class<?> userServiceClazz = UserService.class;
		Class<?>[] paramClasses = new Class<?>[] {String.class};
		Object[] paramValues = new Object[] {"Davy"};
		
		Constructor<?> cons = userServiceClazz.getConstructor(paramClasses);
		
		UserService userService = (UserService) cons.newInstance(paramValues);
		
		userService.addUser();
	}
}

    Comments:

        1) When we regard UserService as an interface, and the real Object created from cons.newInstance(...) as an implementation. Then that would be much more useful.

 

3. Get Methods and Invoke Methods

        1) Possible ways to get Methods from Class object

package edu.xmu.service;

import java.lang.reflect.Method;

import org.junit.Test;

public class UserServiceTest
{
	@Test
	public void test() throws Exception
	{
		Class<?> userServiceClazz = UserService.class;

		Object userService = userServiceClazz.newInstance();

		// Gets all public methods of the class including methods that derived
		// from parents
		// Method[] methods = userServiceClazz.getMethods();
		// for (Method method : methods)
		// {
		// System.out.println(method.getName());
		// }

		// Gets all methods of the class including methods that are private and
		// protected, excluding methods that derived from parents
		// Method[] methods = userServiceClazz.getDeclaredMethods();
		// for (Method method : methods)
		// {
		// System.out.println(method.getName());
		// }

		// getMethod(...) can only get method that is public in current class or
		// its parent class
		// userServiceClass.getMethod("addUser", new Class<?>[] {});
		// Get method by methodName and method Params Types.
		Method method = userServiceClazz.getDeclaredMethod("getUser",
				new Class<?>[] { String.class });
		// As the getUser method is private so we have to setAccessible(true) to
		// suppress access checking
		method.setAccessible(true);
		// Then invoke the method, userService is the instance in which the
		// method will be invoked
		method.invoke(userService, new Object[] { "Davy" });
	}
}

         2) Possible ways to invoke a method in an object (Refer to Upper Example)

 

4. Get Fields From Class Object and Get Field Value From Specific Instance

package edu.xmu.service;

import java.lang.reflect.Field;

import org.junit.Test;

public class UserServiceTest
{
	@Test
	public void test() throws Exception
	{
		Class<?> userServiceClazz = UserService.class;

		UserService userService = (UserService) userServiceClazz.newInstance();
		userService.setUsername("Davy");
		
		Field[] fields = userServiceClazz.getDeclaredFields();
		for(Field field : fields)
		{
			field.setAccessible(true);
			System.out.println(field.get(userService));
		}
	}
}

 

5. Get Annotations

package edu.xmu.service;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import org.junit.Test;

public class UserServiceTest
{
	@Test
	public void test() throws Exception
	{
		Class<?> userServiceClazz = UserService.class;
		
		Method method = userServiceClazz.getDeclaredMethod("getUser", new Class<?>[]{String.class});
	
		Annotation[] annotations = method.getAnnotations();
		for(Annotation annotation : annotations)
		{
			System.out.println(annotation.annotationType());
		}
		// Annotations' length would be zero!
		// Think about the reason!
		// Because the annotation @SuppressWarnings is not @Retention(RetentionPolicy.RUNTIME)
		// It's more likely the RetentionPolicy.SOURCE or RetentionPolicy.COMPILE
		// We can only capture the annotation who is annotated as @Retention(RetentionPolicy.RUNTIME)!
	}
}

 

P.S

        1) Classes used

package edu.xmu.service;

public class UserService
{
	private String username;

	public UserService()
	{
	}
	
	public UserService(String username)
	{
		System.out.println(username);
	}

	public void addUser()
	{
		System.out.println("User added!");
	}

	@SuppressWarnings("unused")
	private void getUser(String username)
	{
		System.out.println("User got!");
	}

	protected void delUser()
	{
		System.out.println("User deleted!");
	}

	public String getUsername()
	{
		return username;
	}

	public void setUsername(String username)
	{
		this.username = username;
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值