Class ClassPool
CtClass objects.
A CtClass object must be obtained from this object.
If get() is called on this object,
it searches various sources represented by ClassPath
to find a class file and then it creates a CtClass object
representing that class file. The created object is returned to the
caller.
Memory consumption memo:
ClassPool objects hold all the CtClasses
that have been created so that the consistency among modified classes
can be guaranteed. Thus if a large number of CtClasses
are processed, the ClassPool will consume a huge amount
of memory. To avoid this, a ClassPool object
should be recreated, for example, every hundred classes processed.
Note that getDefault() is a singleton factory.
Otherwise, detach() in CtClass should be used
to avoid huge memory consumption.
ClassPool hierarchy:
ClassPools can make a parent-child hierarchy as
java.lang.ClassLoaders. If a ClassPool has
a parent pool, get() first asks the parent pool to find
a class file. Only if the parent could not find the class file,
get() searches the ClassPaths of
the child ClassPool. This search order is reversed if
ClassPath.childFirstLookup is true.
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic booleanIf true, the contents of a jar file are cached after the jar file is opened.booleanDetermines the search order.static booleanTurning the automatic pruning on/off.static booleanIf true, unmodified and not-recently-used class files are periodically released for saving memory. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionappendClassPath(String pathname) Appends a directory or a jar (or zip) file to the end of the search path.Appends aClassPathobject to the end of the search path.voidappendPathList(String pathlist) Appends directories and jar files for search.Appends the system search path to the end of the search path.voidClear all the package names recorded byimportPackage().Searches the class path to obtain the URL of the class file specified by classname.Reads a class file from the source and returns a reference to theCtClassobject representing that class file.CtClass[]Reads class files from the source and returns an array ofCtClassobjects representing those class files.getAndRename(String orgName, String newName) Reads a class file and constructs aCtClassobject with a new name.Get the classloader fortoClass(),getAnnotations()inCtClass, etc.getCtClass(String classname) Returns aCtClassobject with the given name.static ClassPoolReturns the default class pool.Returns all the package names recorded byimportPackage().Reads a class file and obtains a compile-time method.Reads a class file from the source and returns a reference to theCtClassobject representing that class file.voidimportPackage(String packageName) Record a package name so that the Javassist compiler searches the package to resolve a class name.insertClassPath(String pathname) Inserts a directory or a jar (or zip) file at the head of the search path.Insert aClassPathobject at the head of the search path.Object[]lookupCflow(String name) Undocumented method.makeAnnotation(String name) Creates a new annotation.makeClass(InputStream classfile) Creates a new class (or interface) from the given class file.makeClass(InputStream classfile, boolean ifNotFrozen) Creates a new class (or interface) from the given class file.Creates a new public class.Creates a new public class.Creates a new class (or interface) from the given class file.Creates a new class (or interface) from the given class file.makeClassIfNew(InputStream classfile) Creates a new class (or interface) from the given class file.makeInterface(String name) Creates a new public interface.makeInterface(String name, CtClass superclass) Creates a new public interface.voidmakePackage(ClassLoader loader, String name) Deprecated.voidrecordInvalidClassName(String name) Deprecated.voidDetatches theClassPathobject from the search path.Converts the given class to ajava.lang.Classobject.Class<?>Converts the class to ajava.lang.Classobject.toClass(CtClass ct, Class<?> neighbor, ClassLoader loader, ProtectionDomain domain) Converts the class to ajava.lang.Classobject.toClass(CtClass ct, ClassLoader loader) Deprecated.toClass(CtClass ct, ClassLoader loader, ProtectionDomain domain) Deprecated.Replaced bytoClass(CtClass,Class,ClassLoader,ProtectionDomain).Class<?>toClass(CtClass ct, MethodHandles.Lookup lookup) Converts the class to ajava.lang.Classobject.toString()Returns the class search path.
-
Field Details
-
childFirstLookup
public boolean childFirstLookupDetermines the search order.If this field is true,
get()first searches the class path associated to thisClassPooland then the class path associated with the parentClassPool. Otherwise, the class path associated with the parent is searched first.The default value is false.
-
doPruning
public static boolean doPruningTurning the automatic pruning on/off.If this field is true,
CtClassobjects are automatically pruned by default whentoBytecode()etc. are called. The automatic pruning can be turned on/off individually for eachCtClassobject.The initial value is false.
-
releaseUnmodifiedClassFile
public static boolean releaseUnmodifiedClassFileIf true, unmodified and not-recently-used class files are periodically released for saving memory.The initial value is true.
-
cacheOpenedJarFile
public static boolean cacheOpenedJarFileIf true, the contents of a jar file are cached after the jar file is opened.The initial value is true.
-
-
Constructor Details
-
ClassPool
public ClassPool()Creates a root class pool. No parent class pool is specified. -
ClassPool
public ClassPool(boolean useDefaultPath) Creates a root class pool. IfuseDefaultPathis true,appendSystemPath()is called. Otherwise, this constructor is equivalent to the constructor taking no parameter.- Parameters:
useDefaultPath- true if the system search path is appended.
-
ClassPool
Creates a class pool.- Parameters:
parent- the parent of this class pool. If this is a root class pool, this parameter must benull.- See Also:
-
-
Method Details
-
getDefault
Returns the default class pool. The returned object is always identical since this method is a singleton factory.The default class pool searches the system search path, which usually includes the platform library, extension libraries, and the search path specified by the
-classpathoption or theCLASSPATHenvironment variable.When this method is called for the first time, the default class pool is created with the following code snippet:
ClassPool cp = new ClassPool(); cp.appendSystemPath();
If the default class pool cannot find any class files, try
ClassClassPath,ModuleClassPath, orLoaderClassPath.- See Also:
-
toString
Returns the class search path. -
importPackage
Record a package name so that the Javassist compiler searches the package to resolve a class name. Don't record thejava.langpackage, which has been implicitly recorded by default.Since version 3.14,
packageNamecan be a fully-qualified class name.Note that
get()inClassPooldoes not search the recorded package. Only the compiler searches it.- Parameters:
packageName- the package name. It must not include the last '.' (dot). For example, "java.util" is valid but "java.util." is wrong.- Since:
- 3.1
-
clearImportedPackages
public void clearImportedPackages()Clear all the package names recorded byimportPackage(). Thejava.langpackage is not removed.- Since:
- 3.1
- See Also:
-
getImportedPackages
Returns all the package names recorded byimportPackage().- Since:
- 3.1
- See Also:
-
recordInvalidClassName
Deprecated.Records a class name that never exists. For example, a package name can be recorded by this method. This would improve execution performance sinceget()quickly throw an exception without searching the class path at all if the given name is an invalid name recorded by this method. Note that searching the class path takes relatively long time.The current implementation of this method performs nothing.
- Parameters:
name- an invalid class name (separeted by dots).
-
lookupCflow
Undocumented method. Do not use; internal-use only.- Parameters:
name- the name of$cflowvariable
-
getAndRename
Reads a class file and constructs aCtClassobject with a new name. This method is useful if you want to generate a new class as a copy of another class (except the class name). For example,getAndRename("Point", "Pair")returns aCtClassobject representingPairclass. The definition ofPairis the same as that ofPointclass except the class name sincePairis defined by readingPoint.class.- Parameters:
orgName- the original (fully-qualified) class namenewName- the new class name- Throws:
NotFoundException
-
get
Reads a class file from the source and returns a reference to theCtClassobject representing that class file. If that class file has been already read, this method returns a reference to theCtClasscreated when that class file was read at the first time.If
classnameends with "[]", then this method returns aCtClassobject for that array type.To obtain an inner class, use "$" instead of "." for separating the enclosing class name and the inner class name.
- Parameters:
classname- a fully-qualified class name.- Throws:
NotFoundException
-
getOrNull
Reads a class file from the source and returns a reference to theCtClassobject representing that class file. This method is equivalent togetexcept that it returnsnullwhen a class file is not found and it never throws an exception.- Parameters:
classname- a fully-qualified class name.- Returns:
- a
CtClassobject ornull. - Since:
- 3.13
- See Also:
-
getCtClass
Returns aCtClassobject with the given name. This is almost equivalent toget(String)except that classname can be an array-type "descriptor" (an encoded type name) such as[Ljava/lang/Object;.Using this method is not recommended; this method should be used only to obtain the
CtClassobject with a name returned fromgetClassInfoinjavassist.bytecode.ClassPool.getClassInforeturns a fully-qualified class name but, if the class is an array type, it returns a descriptor.- Parameters:
classname- a fully-qualified class name or a descriptor representing an array type.- Throws:
NotFoundException- Since:
- 3.8.1
- See Also:
-
find
Searches the class path to obtain the URL of the class file specified by classname. It is also used to determine whether the class file exists.- Parameters:
classname- a fully-qualified class name.- Returns:
- null if the class file could not be found.
- See Also:
-
get
Reads class files from the source and returns an array ofCtClassobjects representing those class files.If an element of
classnamesends with "[]", then this method returns aCtClassobject for that array type.- Parameters:
classnames- an array of fully-qualified class name.- Throws:
NotFoundException
-
getMethod
Reads a class file and obtains a compile-time method.- Parameters:
classname- the class namemethodname- the method name- Throws:
NotFoundException- See Also:
-
makeClass
Creates a new class (or interface) from the given class file. If there already exists a class with the same name, the new class overwrites that previous class.This method is used for creating a
CtClassobject directly from a class file. The qualified class name is obtained from the class file; you do not have to explicitly give the name.- Parameters:
classfile- class file.- Throws:
RuntimeException- if there is a frozen class with the the same name.IOException- See Also:
-
makeClass
public CtClass makeClass(InputStream classfile, boolean ifNotFrozen) throws IOException, RuntimeException Creates a new class (or interface) from the given class file. If there already exists a class with the same name, the new class overwrites that previous class.This method is used for creating a
CtClassobject directly from a class file. The qualified class name is obtained from the class file; you do not have to explicitly give the name.- Parameters:
classfile- class file.ifNotFrozen- throws a RuntimeException if this parameter is true and there is a frozen class with the same name.- Throws:
IOExceptionRuntimeException- See Also:
-
makeClass
Creates a new class (or interface) from the given class file. If there already exists a class with the same name, the new class overwrites that previous class.This method is used for creating a
CtClassobject directly from a class file. The qualified class name is obtained from the class file; you do not have to explicitly give the name.- Parameters:
classfile- class file.- Throws:
RuntimeException- if there is a frozen class with the the same name.- Since:
- 3.20
-
makeClass
Creates a new class (or interface) from the given class file. If there already exists a class with the same name, the new class overwrites that previous class.This method is used for creating a
CtClassobject directly from a class file. The qualified class name is obtained from the class file; you do not have to explicitly give the name.- Parameters:
classfile- class file.ifNotFrozen- throws a RuntimeException if this parameter is true and there is a frozen class with the same name.- Throws:
RuntimeException- Since:
- 3.20
-
makeClassIfNew
Creates a new class (or interface) from the given class file. If there already exists a class with the same name, this method returns the existing class; a new class is never created from the given class file.This method is used for creating a
CtClassobject directly from a class file. The qualified class name is obtained from the class file; you do not have to explicitly give the name.- Parameters:
classfile- the class file.- Throws:
IOExceptionRuntimeException- Since:
- 3.9
- See Also:
-
makeClass
Creates a new public class. If there already exists a class with the same name, the new class overwrites that previous class.If no constructor is explicitly added to the created new class, Javassist generates constructors and adds it when the class file is generated. It generates a new constructor for each constructor of the super class. The new constructor takes the same set of parameters and invokes the corresponding constructor of the super class. All the received parameters are passed to it.
- Parameters:
classname- a fully-qualified class name.- Throws:
RuntimeException- if the existing class is frozen.
-
makeClass
Creates a new public class. If there already exists a class/interface with the same name, the new class overwrites that previous class.If no constructor is explicitly added to the created new class, Javassist generates constructors and adds it when the class file is generated. It generates a new constructor for each constructor of the super class. The new constructor takes the same set of parameters and invokes the corresponding constructor of the super class. All the received parameters are passed to it.
- Parameters:
classname- a fully-qualified class name.superclass- the super class.- Throws:
RuntimeException- if the existing class is frozen.
-
makeInterface
Creates a new public interface. If there already exists a class/interface with the same name, the new interface overwrites that previous one.- Parameters:
name- a fully-qualified interface name.- Throws:
RuntimeException- if the existing interface is frozen.
-
makeInterface
Creates a new public interface. If there already exists a class/interface with the same name, the new interface overwrites that previous one.- Parameters:
name- a fully-qualified interface name.superclass- the super interface.- Throws:
RuntimeException- if the existing interface is frozen.
-
makeAnnotation
Creates a new annotation. If there already exists a class/interface with the same name, the new interface overwrites that previous one.- Parameters:
name- a fully-qualified interface name. Or null if the annotation has no super interface.- Throws:
RuntimeException- if the existing interface is frozen.- Since:
- 3.19
-
appendSystemPath
Appends the system search path to the end of the search path. The system search path usually includes the platform library, extension libraries, and the search path specified by the-classpathoption or theCLASSPATHenvironment variable.- Returns:
- the appended class path.
-
insertClassPath
Insert aClassPathobject at the head of the search path.- Returns:
- the inserted class path.
- See Also:
-
appendClassPath
Appends aClassPathobject to the end of the search path.- Returns:
- the appended class path.
- See Also:
-
insertClassPath
Inserts a directory or a jar (or zip) file at the head of the search path.- Parameters:
pathname- the path name of the directory or jar file. It must not end with a path separator ("/"). If the path name ends with "/*", then all the jar files matching the path name are inserted.- Returns:
- the inserted class path.
- Throws:
NotFoundException- if the jar file is not found.
-
appendClassPath
Appends a directory or a jar (or zip) file to the end of the search path.- Parameters:
pathname- the path name of the directory or jar file. It must not end with a path separator ("/"). If the path name ends with "/*", then all the jar files matching the path name are appended.- Returns:
- the appended class path.
- Throws:
NotFoundException- if the jar file is not found.
-
removeClassPath
Detatches theClassPathobject from the search path. The detachedClassPathobject cannot be added to the path again. -
appendPathList
Appends directories and jar files for search.The elements of the given path list must be separated by colons in Unix or semi-colons in Windows.
- Parameters:
pathlist- a (semi)colon-separated list of the path names of directories and jar files. The directory name must not end with a path separator ("/").- Throws:
NotFoundException- if a jar file is not found.
-
toClass
Converts the given class to ajava.lang.Classobject. Once this method is called, further modifications are not allowed any more. To load the class, this method uses the context class loader of the current thread. It is obtained by callinggetClassLoader().This behavior can be changed by subclassing the pool and changing the
getClassLoader()method. If the program is running on some application server, the context class loader might be inappropriate to load the class.This method is provided for convenience. If you need more complex functionality, you should write your own class loader.
Warining: This method should not be used in Java 11 or later. Use
toClass(CtClass,Class).Warining: A Class object returned by this method may not work with a security manager or a signed jar file because a protection domain is not specified.
-
getClassLoader
Get the classloader fortoClass(),getAnnotations()inCtClass, etc.The default is the context class loader.
- Returns:
- the classloader for the pool
- See Also:
-
toClass
Deprecated.Replaced bytoClass(CtClass,Class,ClassLoader,ProtectionDomain). A subclass ofClassPoolthat has been overriding this method should be modified. It should overridetoClass(CtClass,Class,ClassLoader,ProtectionDomain).Converts the class to ajava.lang.Classobject. Do not override this method any more at a subclass becausetoClass(CtClass)will never calls this method.Warining: A Class object returned by this method may not work with a security manager or a signed jar file because a protection domain is not specified.
- Throws:
CannotCompileException
-
toClass
public Class toClass(CtClass ct, ClassLoader loader, ProtectionDomain domain) throws CannotCompileException Deprecated.Replaced bytoClass(CtClass,Class,ClassLoader,ProtectionDomain).Converts the class to ajava.lang.Classobject. Once this method is called, further modifications are not allowed any more.The class file represented by the given
CtClassis loaded by the given class loader to construct ajava.lang.Classobject. Since a private method on the class loader is invoked through the reflection API, the caller must have permissions to do that.An easy way to obtain
ProtectionDomainobject is to callgetProtectionDomain()injava.lang.Class. It returns the domain that the class belongs to.This method is provided for convenience. If you need more complex functionality, you should write your own class loader.
- Parameters:
ct- the class converted intojava.lang.Class.loader- the class loader used to load this class. For example, the loader returned bygetClassLoader()can be used for this parameter.domain- the protection domain for the class. If it is null, the default domain created byjava.lang.ClassLoaderis used.- Throws:
CannotCompileException- Since:
- 3.3
- See Also:
-
toClass
Converts the class to ajava.lang.Classobject. Once this method is called, further modifications are not allowed any more.This method is available in Java 9 or later. It loads the class by using
java.lang.invoke.MethodHandleswithneighbor.- Parameters:
ct- the class converted intojava.lang.Class.neighbor- a class belonging to the same package that the converted class belongs to.- Throws:
CannotCompileException- Since:
- 3.24
-
toClass
Converts the class to ajava.lang.Classobject. Once this method is called, further modifications are not allowed any more.This method is available in Java 9 or later. It loads the class by using the given
java.lang.invoke.MethodHandles.Lookup.- Parameters:
ct- the class converted intojava.lang.Class.- Throws:
CannotCompileException- Since:
- 3.24
-
toClass
public Class toClass(CtClass ct, Class<?> neighbor, ClassLoader loader, ProtectionDomain domain) throws CannotCompileException Converts the class to ajava.lang.Classobject. Once this method is called, further modifications are not allowed any more.When the JVM is Java 11 or later, this method loads the class by using
java.lang.invoke.MethodHandleswithneighbor. The other argumentsloaderanddomainare not used; so they can be null.Otherwise, or when
neighboris null, the class file represented by the givenCtClassis loaded by the given class loader to construct ajava.lang.Classobject. Since a private method on the class loader is invoked through the reflection API, the caller must have permissions to do that.An easy way to obtain
ProtectionDomainobject is to callgetProtectionDomain()injava.lang.Class. It returns the domain that the class belongs to.If your program is for only Java 9 or later, don't use this method. Use
toClass(CtClass,Class)ortoClass(CtClass,java.lang.invoke.MethodHandles.Lookup).- Parameters:
ct- the class converted intojava.lang.Class.neighbor- a class belonging to the same package that the converted class belongs to. It can be null.loader- the class loader used to load this class. For example, the loader returned bygetClassLoader()can be used for this parameter.domain- the protection domain for the class. If it is null, the default domain created byjava.lang.ClassLoaderis used.- Throws:
CannotCompileException- Since:
- 3.24
- See Also:
-
makePackage
Deprecated.Defines a new package. If the package is already defined, this method performs nothing.You do not necessarily need to call this method. If this method is called, then
getPackage()on theClassobject returned bytoClass()will return a non-null object.The jigsaw module introduced by Java 9 has broken this method.
- Parameters:
loader- the class loader passed totoClass()or the default one obtained bygetClassLoader().name- the package name.- Throws:
CannotCompileException- Since:
- 3.16
- See Also:
-
toClass(CtClass,Class,ClassLoader,ProtectionDomain).