Listing available classes in current classpath using a command line tool

久未见 提交于 2019-12-23 05:13:48

问题


I need to check if a specific class is available from current directory using a default JRE/JDK command line tool.

I could build my own class to list it or check if a specific class is reacheble from current directory and current CLASSPATH environment variable, but this option is not available since I need to check if a specific class name is available or not in a protected production environment (read only).


回答1:


You can use javap:

$ javap java.lang.String
Compiled from "String.java"
public final class java.lang.String implements java.io.Serializable
[...]


$ javap no.such.Class
Error:  class not found: no.such.Class



回答2:


You can use the -verbose option of the java command and search for the fully qualified name of a specific class.

$ java -verbose -jar MyProgram.jar | grep "java.lang.String"
[Loaded java.lang.String from /Library/Java/…/Contents/Home/jre/lib/rt.jar]
[Loaded java.lang.StringBuffer from /Library/Java/…/Contents/Home/jre/lib/rt.jar]
…

Addendum: I want to check the class availability for an environment.

If you are running from the java command line, either the paths specified in the -classpath option or the CLASSPATH environment variable will be searched. If you are running from a JAR, the manifest's Class-Path attribute, for example, supplants these settings.

If you are trying to find a required JAR that may not be accessible in these ways, you'll have to search the file system. I use a combination of find, jar and grep, typically focussing on paths defined in system properties such as java.endorsed.dirs and java.ext.dirs; several related approaches are shown here.



来源:https://stackoverflow.com/questions/27159005/listing-available-classes-in-current-classpath-using-a-command-line-tool

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