JAVA中的反射机制

xiaoxiao2023-01-26  13

[url=http://hi.baidu.com/mgp1030/blog/item/d34509edf0787bd1b21cb167.html]原文链接[/url] import java.lang.reflect.Constructor;import java.lang.reflect.Method;public class ReflectTest { public static void main(String[] args) throws Exception { String str = "sun.mgp.Customer"; Class<?> c = Class.forName(str); // 获取构造函数及其中参数 Constructor<?>[] con = c.getConstructors(); System.out.println("构造函数名为:" + con[0].getName()); for (int i = 0; i < con.length; i++) { System.out.println("构造函数为:" + con); Class<?>[] cl = con[i].getParameterTypes(); for (int j = 0; j < cl.length; j++) { System.out.println("参数为:" + cl[j].getName()); } } System.out.println("--------------------------"); // 获取方法及参数 Method[] met = c.getMethods(); for (int i = 0; i < met.length; i++) { System.out.println(met[i].getName()); Class<?>[] cm = met[i].getParameterTypes(); for (int j = 0; j < cm.length; j++) System.out.println("参数为:" + cm[j].getName()); } }}class NewInstn { public static void main(String[] args) { String str = "sun.mgp.Customer"; try { Class<?> c = Class.forName(str); c.newInstance();// 获得无参构造函数的实例 Constructor<?> con = c.getConstructor(new Class[] {});// 得到不带参数的构造函数 con.newInstance(new Object[] {}); // 带参构造函数 Constructor<?> conr = c.getConstructor(new Class[] { Class.forName("java.lang.String"), Class.forName("java.lang.String") }); Object objr = conr.newInstance(new Object[] { "hello", "world" }); // 调用类中的test方法 Method met = c.getMethod("test", new Class[] {}); met.invoke(objr); } catch (Exception ex) { ex.printStackTrace(); } }}class Customer { public Customer() { System.out.println("无参构造函数被调用"); } public Customer(String a, String p) { System.out.println("带参构造函数被调用"); } public void printInfo() { System.out.println("hello,world!"); } public void test() { System.out.println("this is test"); }}
转载请注明原文地址: https://www.6miu.com/read-4980783.html

最新回复(0)