[英]is there a way to check if a class has the main method?
I'm trying to get the list of all classes in a project in Java and I would like to identify the class where the main method is located. 我正在尝试获取Java项目中所有类的列表,我想确定main方法所在的类。 Is there a way to be able to identify that a class is implementing the main method, without actually looking at the code of the class itself?
有没有一种方法可以识别类是否正在实现main方法,而无需实际查看类本身的代码?
I've implemented the following but the return value is always being false. 我实现了以下内容,但返回值始终为false。 does anyone know why this is happening?
有谁知道为什么会这样?
Class<?> c = "edu.tool.parsing.A".getClass();
boolean hasMain = true;
try {
c.getMethod("main", String[].class);
hasMain=true;
} catch (SecurityException e) {
hasMain = true;
} catch (NoSuchMethodException e) {
hasMain=false;
}
Programmatically: 以编程方式:
Class.getClass("com.mycompany.MyClass").getMethod("main", String[].class)
Or alternatively you can use command line utility javap
that you can find in your JDK bin directory. 或者,您可以使用在JDK bin目录中找到的命令行实用程序
javap
。
If you have the class name, then you can try to reflect the main
method. 如果您具有类名,则可以尝试反映
main
方法。
Trivial (inclomplete) approach: 普通(渐进式)方法:
private static hasMainMethod(Class<?> clazz) throws Exception {
Method[] methods = clazz.getMethods();
for (Mehthod method:methods) {
if (method.getName().equals("main") {
// Now we have to verify the method signature!
return true;
}
}
return false;
}
There may be more than one such class. 这样的类可能不止一个。 There may be dozens.
可能有几十个。 Why don't you know the entry point in advance?
您为什么不提前知道入口点? You might be better off looking at the Main-Class entry in the JAR Manifest.
您最好查看JAR清单中的Main-Class条目。
Load your project in a IDE (I have worked with IDEA) then, add a local run, IDEA will list you all classes with main method. 然后将您的项目加载到IDE中(我曾与IDEA一起工作过),然后添加本地运行,IDEA将列出您所有带有main方法的类。
If you don't have sources and there are just jar files, that's ok, just add the jar files as a library of a project and then create a RUN. 如果您没有源并且只有jar文件,那么可以,只需将jar文件添加为项目的库,然后创建RUN。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.