I am attempting to get a simple Javassist example going. Consider the following code. Assume variable classPath points to a correct class folder that contains the required .class file.
When running, the first invocation of classPool.get() succeeds and the second fails. The spec of method ClassPool.get() requires a fully-qualified class name. Why is that?
package com.domain.jcp;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.NotFoundException;
public class Jcp {
public static void main(String[] args) throws NotFoundException {
ClassPool classPool = ClassPool.getDefault();
String classPath = "[CORRECT PATH TRUNK]\\target\\test-classes\\com\\domain\\jcp";
classPool.insertClassPath(classPath);
CtClass clazz1 = classPool.get("JcpTest");
CtClass clazz2 = classPool.get("com.domain.jcp.JcpTest");
}
}
The folder layout is a standard layout for a Maven project.
You simply need to use the correct classpath. This is wrong, because you are pointing into a package subdirectory rather than straight to the root:
String classPath = "[CORRECT PATH TRUNK]\\target\\test-classes\\com\\domain\\jcp";
This is correct:
String classPath = "[CORRECT PATH TRUNK]\\target\\test-classes";
Then you need to use the fully qualified package name, i.e. of these
CtClass clazz1 = classPool.get("JcpTest");
CtClass clazz2 = classPool.get("com.domain.jcp.JcpTest");
only the latter is correct, while the former is not.
Update: Here is what happens if you misunderstand what a Java classpath is:
import javassist.ClassPool;
import javassist.CtClass;
import javassist.NotFoundException;
public class JavassistGetClass {
private static final String BASE_PATH = "...";
public static void main(String[] args) throws NotFoundException {
ClassPool classPool = ClassPool.getDefault();
// How to correctly use a classpath in Javassist
String classPath = BASE_PATH + "\\target\\classes";
classPool.insertClassPath(classPath);
CtClass ctClass = classPool.get("de.scrum_master.stackoverflow.q70786275.Application");
System.out.println("Correct package name: " + ctClass.getPackageName());
// How NOT to use a classpath in Javassist (or anywhere else)
String classPathIncorrect = BASE_PATH + "\\target\\classes\\de\\scrum_master\\stackoverflow\\q70786275";
classPool.insertClassPath(classPathIncorrect);
CtClass ctClassIncorrect = classPool.get("Application");
System.out.println("Incorrect package name: " + ctClassIncorrect.getPackageName());
}
}
Console log:
Correct package name: de.scrum_master.stackoverflow.q70786275
Incorrect package name: null