java 在Java中动态加载一个类并调用一个方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11594797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 05:42:47  来源:igfitidea点击:

Dynamically load a Class and invoke a method in Java

javaclassreflectionmethodsinvoke

提问by lukuluku

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

假设我想在 java 中动态加载一个类并调用它的start()(没有参数)方法:

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

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

这是一个好的/安全的方法吗?

采纳答案by ???v?т?

Looks good to me.

对我来说看上去很好。

If you're doing a lot of reflection-related code you might look at Apache Beanutilsor Apache OGNLor something similar.

如果您正在编写大量与反射相关的代码,您可能会查看 Apache Beanutils或 Apache OGNL或类似的东西。

回答by SALMAN

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.

反射是在运行时处理Java 类的一种非常有用的方法,它可以用于在运行时加载Java 类、调用其方法或分析该类。

Try this example.

试试这个例子。

This will surely help you.

这肯定会帮助你。

How To Use Reflection To Call Java Method At Runtime

如何在运行时使用反射调用 Java 方法

Thanks

谢谢