![](/img/trans.png)
[英]Is there a way to check if a class has a method and then invoke it on an already existing instance of the object?
[英]is there a way to check if a class has the main method?
我正在嘗試獲取Java項目中所有類的列表,我想確定main方法所在的類。 有沒有一種方法可以識別類是否正在實現main方法,而無需實際查看類本身的代碼?
我實現了以下內容,但返回值始終為false。 有誰知道為什么會這樣?
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;
}
以編程方式:
Class.getClass("com.mycompany.MyClass").getMethod("main", String[].class)
或者,您可以使用在JDK bin目錄中找到的命令行實用程序javap
。
如果您具有類名,則可以嘗試反映main
方法。
普通(漸進式)方法:
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;
}
這樣的類可能不止一個。 可能有幾十個。 您為什么不提前知道入口點? 您最好查看JAR清單中的Main-Class條目。
然后將您的項目加載到IDE中(我曾與IDEA一起工作過),然后添加本地運行,IDEA將列出您所有帶有main方法的類。
如果您沒有源並且只有jar文件,那么可以,只需將jar文件添加為項目的庫,然后創建RUN。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.