Java: Checking while run time if class exists [duplicate]

混江龙づ霸主 提交于 2019-12-20 03:13:18

问题


I am working on a software which depends on an 3rd party library. Due to license agreements this library cannot be shipped along with the software and the user has to have the library already locally when starting the program.

Is there any way to check if this particular library exist in the class path and can be loaded? If not I would like to offer a dialog to allow the user pointing to the location and add this location to the class path dynamically.

Thanks for your help!


回答1:


Try this:

try {
    Class<?> clazz = Class.forName("com.acme.SecretClass");
} catch (ClassNotFoundException e) {
    // Show dialog
}



回答2:


The fastest way in terms of computing time I know is:

public class ClazzUtil {

    public static boolean isClassnameAvailable(String clazzName) {
        try {
            Class.forName(clazzName, false, ClazzUtil.class.getClassLoader());
        } catch (LinkageError | ClassNotFoundException e) {
            return false;
        }
        return true;
    }

}



回答3:


If a class is not present at runtime,it will throw ClassNotFoundException. You can check for this in the following way.

try {
    Class cls = Class.forName("yourClassName");
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}



回答4:


Just solved the problem in my code, supper useful without raising an exception.

@SuppressWarnings("finally")
private boolean existClass(String className){
    Class<?> classname= null;
    try {
        classname = Class.forName(className);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } finally{
        if(classname == null) 
            return false;
        else 
            return true;
    }
}


来源:https://stackoverflow.com/questions/27060999/java-checking-while-run-time-if-class-exists

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