运行时获得所有的类

1、如果使用spring, 可以使用以下方式获得spring context中的所有的类:

public class GameReflect implements ApplicationContextAware {
	public ApplicationContext applicationContext;

@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}
public void getAllClass(){
        applicationContext.getBeansOfType(GameBaseAction.class);
}
}

2、除此之外,也可以从classloader中使用一种hack方式获得所有的类:

package cn.joylab.service;

import java.lang.reflect.Field;
import java.util.Vector;

public class ClassLoaderTest extends GameBaseManagerTestCase {
	@org.junit.Test
	public void test1() {
		try {
			Field f = ClassLoader.class.getDeclaredField("classes");
			f.setAccessible(true);

			ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

			Vector<Class> classes = (Vector<Class>) f.get(classLoader);
			for (Class c : classes) {
				System.out.println(c);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
发表评论?

0 条评论。

发表评论


注意 - 你可以用以下 HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>


Warning: Use of undefined constant XML - assumed 'XML' (this will throw an Error in a future version of PHP) in /opt/wordpress/wp-content/plugins/wp-syntaxhighlighter/wp-syntaxhighlighter.php on line 1048