mardi 1 novembre 2022

How do I add java files at runtime and compile them during runtime?

I have to check whether a method exists or not in a java class but this java file is not present in the current classpath.

for example

I am running a java code then I have to check presence of java method which is not present in current project(i.e those java files are not compiled) those java files are present at a different location.

My Approach:

1. Adding those files to class path

2. compling each java file

3. then checking the presence of methods in a class specified

Codes:

public static void setClassPath(String path) {
    String cp = System.getProperty("java.class.path");
    cp = cp.replace(";.;", "");
    System.out.println("Before >>>>>>>>>>>>>>>>" + cp);
    String newcp = cp + System.getProperty("path.separator") + path;
    System.setProperty("java.class.path", newcp);
    System.out.println("After>>>>>>>>>>>>>>>>" + System.getProperty("java.class.path"));

}

public static void compileJavaFile() {
     // Compile source file.
        for (File f : javaFiles) {
            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            compiler.run(null, null, null, f.getAbsolutePath());
        }
    }




 public static boolean isMethodExist(String className, String methodName) {
        Class<?> classToCheck = null;
        try {
            classToCheck = Class.forName(className);
        } catch (ClassNotFoundException e) {

            e.printStackTrace();
            return false;
        }
        try {

            Method[] declaredMethods = classToCheck.getDeclaredMethods();

            for (Method method : declaredMethods) {
                if (method.getName().equals(methodName)) {
                    return true;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return false;
    }




Aucun commentaire:

Enregistrer un commentaire