脚本宝典收集整理的这篇文章主要介绍了Java中的反射创建一个新实例,并将引用变量类型设置为新的实例类名称,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Foo { public void PRintamessage() { System.out.println(toString()+":a message"); } public void printAnotherMessage(String theString) { System.out.println(toString()+":another message:" + theString); } public static void main(String[] args) { Class c = null; try { c = Class.forName("Foo"); Method method1 = c.getDeclaredMethod("printAMessage", new Class[]{}); Method method2 = c.getDeclaredMethod("printAnotherMessage", new Class[]{String.class}); Object o = c.newInstance(); System.out.println("this is my instance:" + o.toString()); method1.invoke(o); method2.invoke(o, "this is my message, From a config file, of course"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException nsme){ nsme.printStackTrace(); } catch (IllegalAccessException iae) { iae.printStackTrace(); } catch (InstantiationException ie) { ie.printStackTrace(); } catch (InvocationTargetException ITe) { ite.printStackTrace(); } } }
以上是脚本宝典为你收集整理的Java中的反射创建一个新实例,并将引用变量类型设置为新的实例类名称全部内容,希望文章能够帮你解决Java中的反射创建一个新实例,并将引用变量类型设置为新的实例类名称所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。