本文主要是介绍反射获取类的实例Class.forName,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
public class Manager {private String name = "xq";public void getName() {System.out.println(name);}public void setName(String name, int a) {this.name = name + a;}/*** 测试** @param args*/public static void main(String[] args) {try {test1();System.out.println("--------------------------------");test2();System.out.println("--------------------------------");test3();System.out.println("--------------------------------");} catch (Exception e) {System.out.println(e);}}/*** 通过 [类.class] 获得Class对象** @throws Exception*/private static void test1() throws Exception {Class clazz = Manager.class;Object object = clazz.newInstance();handle(clazz, object, 1);}/*** 通过 [实例名.getClass()] 获得Class对象** @throws Exception*/private static void test2() throws Exception {Manager object = new Manager();Class clazz = object.getClass();handle(clazz, object, 2);}/*** 通过 [Class.forName(全路径)] 获得Class对象** @throws Exception*/private static void test3() throws Exception {Class clazz = Class.forName("Manager");Object object = clazz.newInstance();handle(clazz, object, 3);}private static void handle(Class clazz, Object object, int i) throws Exception {Method getName = clazz.getDeclaredMethod("getName", new Class[]{});Method setName = clazz.getDeclaredMethod("setName", new Class[]{String.class, int.class});getName.invoke(object); // 获取默认值setName.invoke(object, "Setting new ", i); // 设置getName.invoke(object); // 获取最新}
}
这篇关于反射获取类的实例Class.forName的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!