通过字符串动态创建对象,通过字符串动态使用对象方法
package com.hmdp.service.动态调用方法;
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) throws Exception {
String name = "javax.swing.JFrame";
Class<?> clazz = Class.forName(name);
Object obj = clazz.getConstructor().newInstance();
Method mth = clazz.getMethod("setTitle", String.class);
mth.invoke(obj, "我的窗口");
System.out.println(obj);
Method setSize = clazz.getMethod("setSize", int.class, int.class);
setSize.invoke(obj, 300, 300);
System.out.println(obj);
}
}