`
DavyJones2010
  • 浏览: 148273 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

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;
	}

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics