通过反射获取java类的实例

package com.test.springmvc.test;

import org.springframework.beans.BeanUtils;
import org.springframework.util.ClassUtils;

public class MainTest {

	public static void main(String[] args) throws Exception {
		MainTest test = test();
		test.sys();

		MainTest test1 = test1();
		test1.sys();
	}

	/**
	 * 第1种方法,直接newInstance
	 * 
	 * @return
	 * @throws Exception
	 */
	public static  MainTest test() throws ClassNotFoundException,
			LinkageError, InstantiationException, IllegalAccessException {
		Class clazz = (Class) ClassUtils.forName(
				"com.test.springmvc.test.MainTest",
				ClassUtils.getDefaultClassLoader());
		return clazz.newInstance();
	}

	/**
	 * 第2种方法,通过BeanUtils.instantiate
	 * 
	 * @return
	 * @throws Exception
	 */
	public static  MainTest test1() throws Exception {
		Class clazz = (Class) ClassUtils.forName(
				"com.test.springmvc.test.MainTest",
				ClassUtils.getDefaultClassLoader());
		return BeanUtils.instantiate(clazz);
	}

	public void sys() {
		System.out.println("test");
	}
}

你可能感兴趣的:(spring,源码)