Dynamically load a Class and invoke a method in Java

有些话、适合烂在心里 提交于 2019-12-23 13:06:52

问题


Lets say i want to dynamically load a class in java and call it's start() (has no params) method:

Class<?> c = Class.forName("AbuseMe");
c.getMethod("start").invoke(c.newInstance());

Would this be a good/safe way to do it?


回答1:


Looks good to me.

If you're doing a lot of reflection-related code you might look at Apache Beanutils or Apache OGNL or something similar.




回答2:


Reflection is a very useful approach to deal with the Java class at runtime, it can be use to load the Java class, call its methods or analysis the class at runtime.

Try this example.

This will surely help you.

How To Use Reflection To Call Java Method At Runtime

Thanks



来源:https://stackoverflow.com/questions/11594797/dynamically-load-a-class-and-invoke-a-method-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!