Class Classes

java.lang.Object
org.zkoss.lang.Classes

public class Classes extends Object
Utilities to handle java.lang.Class
Author:
tomyeh
  • Field Details

    • B_GET

      public static final int B_GET
      Search the get method; not imply B_METHODONLY.
      See Also:
    • B_SET

      public static final int B_SET
      Search the set method; not imply B_METHODONLY.
      See Also:
    • B_PUBLIC_ONLY

      public static final int B_PUBLIC_ONLY
      Only search for public methods or fields.
      See Also:
    • B_METHOD_ONLY

      public static final int B_METHOD_ONLY
      Only search for methods; excluding fields.
      See Also:
  • Constructor Details

    • Classes

      public Classes()
  • Method Details

    • newInstance

      public static final Object newInstance(Class<?> cls, Class<?>[] argTypes, Object[] args) throws NoSuchMethodException, InstantiationException, InvocationTargetException, IllegalAccessException
      Instantiates a new instance of the specified class with the specified arguments and argument types.

      Note only public constructors are searched.

      Parameters:
      cls - the class of the instance to create
      argTypes - the argument types of the constructor to invoke
      args - the arguments to initialize the instance
      Returns:
      the new instance
      Throws:
      NoSuchMethodException - if a matching method is not found
      InstantiationException - if the class that declares the underlying constructor represents an abstract class
      InvocationTargetException - if the underlying constructor throws an exception
      IllegalAccessException
      See Also:
    • newInstance

      Instantiates a new instance of the specified class with the specified argument.

      It searches all constructors for the first one that matches the specified arguments.

      Throws:
      NoSuchMethodException
      InstantiationException
      InvocationTargetException
      IllegalAccessException
      Since:
      3.0.1
    • newInstance

      Instantiates a new instance of the specified class name with the specified arguments.

      It uses Class.forName to get the class.

      Parameters:
      clsName - the class name of the instance to create
      argTypes - the argument types of the constructor to invoke
      args - the arguments to initialize the instance
      Returns:
      the new instance
      Throws:
      NoSuchMethodException - if a matching method is not found
      InstantiationException - if the class that declares the underlying constructor represents an abstract class
      InvocationTargetException - if the underlying constructor throws an exception
      ClassNotFoundException - if the specified class name is not a class
      IllegalAccessException
      See Also:
    • newInstanceByThread

      public static final Object newInstanceByThread(String clsName, Class<?>[] argTypes, Object[] args) throws NoSuchMethodException, InstantiationException, InvocationTargetException, ClassNotFoundException, IllegalAccessException
      Creates and initializes a new instance of the specified class name with the specified arguments, by use of forNameByThread(java.lang.String).

      It uses forNameByThread(java.lang.String) to get the class.

      Parameters:
      clsName - the class name of the instance to create
      argTypes - the argument types of the constructor to invoke
      args - the arguments to initialize the instance
      Returns:
      the new instance
      Throws:
      NoSuchMethodException - if a matching method is not found
      InstantiationException - if the class that declares the underlying constructor represents an abstract class
      InvocationTargetException - if the underlying constructor throws an exception
      ClassNotFoundException - if the specified class name is not a class
      IllegalAccessException
      See Also:
    • newInstanceByThread

      Creates and initializes a new instance of the specified class name with default constructor, by use of forNameByThread(java.lang.String).
      Throws:
      NoSuchMethodException
      InstantiationException
      InvocationTargetException
      ClassNotFoundException
      IllegalAccessException
    • forNameByThread

      public static final Class<?> forNameByThread(String clsName) throws ClassNotFoundException
      Returns the Class object of the specified class name, using the current thread's context class loader and the class will be initialized by default.

      It first tries Thread.currentThread().getContextClassLoader(), and then Classes's class loader if not found.

      In additions, it handles the primitive types, such as int and double.

      Parameters:
      clsName - fully qualified name of the desired class
      Returns:
      the Class object representing the desired class
      Throws:
      ClassNotFoundException - if the class cannot be located by the specified class loader
      See Also:
    • forNameByThread

      public static final Class<?> forNameByThread(String clsName, boolean initialize) throws ClassNotFoundException
      Returns the Class object of the specified class name, using the current thread's context class loader.

      It first tries Thread.currentThread().getContextClassLoader(), and then Classes's class loader if not found.

      In additions, it handles the primitive types, such as int and double.

      Parameters:
      clsName - fully qualified name of the desired class
      initialize - if true the class will be initialized.
      Returns:
      the Class object representing the desired class
      Throws:
      ClassNotFoundException - if the class cannot be located by the specified class loader
      Since:
      10.0.0
      See Also:
    • existsByThread

      public static final boolean existsByThread(String clsnm)
      Returns whether the specified class exists for the current thread's context class loader.
      Parameters:
      clsnm - the class name to test
      Since:
      3.0.7
    • toInternalForm

      public static final String toInternalForm(String clsName)
      Change class name to internal form (e.g. byte[] -> [B]). If already in internal form, then just return it.
    • getTopmostInterface

      public static Class<?> getTopmostInterface(Class<?> cls, Class<?> subIF)
      Gets the topmost interface of the specified class or interface that implements or extends the specified interface. For example, if A extends B, and C implements A, then getTopInterface(C, B) returns A.

      The interfaces implemented by the specified class is checked first, and then the subclass.

      Parameters:
      cls - the class or interface
      subIF - the sub-interface
      Returns:
      the topmost interface extending subIF, or null if subIF is not implemented by cls
    • getAllInterfaces

      public static Class<?>[] getAllInterfaces(Class<?> cls)
      Returns all interfaces that are implemented by the specified class.

      Unlike Class.getInterfaces(), it recursively searches for all derived classes.

    • containsMethod

      public static final boolean containsMethod(Class<?> cls, String name, Class<?>[] paramTypes)
      Tests whether a class contains the specified method. Only public methods are tested.
      Parameters:
      cls - the class to test
      name - the method name
      paramTypes - the list of parameter types
      Returns:
      true if it contains the method
    • correctFieldName

      public static final String correctFieldName(String name)
      Corrects a string to a valid Java name. Currently, it only removes '-' and capitalizes the succeeding character. Example, 'field-name' becomes 'fieldName'.
    • toMethodName

      public static final String toMethodName(String attrName, String prefix)
      Convert an attribute name, returned by toAttributeName, to a method name.

      toMethodName("true", "is") => "isTrue"
      toMethodName("true", "") => "true"

      Parameters:
      attrName - the attribute name
      prefix - the prefix; one of is, get and set
      Returns:
      the method name
      See Also:
    • isAttribute

      public static final boolean isAttribute(String methodName)
      Tests if a method name is an attribute, i.e., prefixing with is, get or set. Caller could then test if it is a setter or getter by charAt(0)=='s'.

      Note 'set' is considered as an attribute, whose name is an empty string.

      Parameters:
      methodName - the method name to test
      Returns:
      true if it is setter or getter
    • toAttributeName

      public static final String toAttributeName(String methodName)
      Converts a method name to an attribute name by removing the prefix is, get or set, or null if it doesn't start with is, get or set.

      The code is optimized for better performance.

      Parameters:
      methodName - the method name
      Returns:
      the attribute name; null if it is not an attribute name
      See Also:
    • parseMethod

      public static final Classes.MethodInfo parseMethod(String signature) throws IllegalSyntaxException
      Gets the method information from a signature. It returns a method info with the return type, method name and two collections of arguments type and arguments name.
      Parameters:
      signature - the method signature.
      Returns:
      MethodInfo The method information including return type, method name and two collections for argument type and arguments name.
      Throws:
      IllegalSyntaxException
    • getMethodBySignature

      public static final Method getMethodBySignature(Class<?> cls, String signature, Collection<String> params, ClassResolver resolver) throws NoSuchMethodException, ClassNotFoundException
      Gets the method based on the signature with a class resolver. It also returns the parameter names to the params list.

      Like getMethodInPublic(Class, String, Class[]), it returns only public method in a public class/interface.

      For example, "find(java.lang.String name)" will return the method with one String-typed argument and params will hold "name". The return type is optional (actually ignored).

      If params is null, the parameter names are not returned and the signature could be simplified as "find(java.lang.String)".

      A cache mechanism is implemented, so you don't need to cache it again in the caller.

      Parameters:
      cls - the class to look
      signature - the method signature; the return type is optional.
      Notice that the argument's type must be a full-qualified class name, unless its package is java.lang or it can be resolved by resolver.
      params - the collection to hold the parameter names returned; null means no parameter names to return
      resolver - the class resolver used to resolve the class specified in the signature. Ignored if null.
      Throws:
      NoSuchMethodException
      ClassNotFoundException
      Since:
      6.0.0
    • getMethodBySignature

      public static final Method getMethodBySignature(Class<?> cls, String signature, Collection<String> params) throws NoSuchMethodException, ClassNotFoundException
      Gets the method based on the signature. It also returns the parameter names to the params list.

      Like getMethodInPublic(Class, String, Class[]), it returns only public method in a public class/interface.

      For example, "find(java.lang.String name)" will return the method with one String-typed argument and params will hold "name". The return type is optional (actually ignored).

      If params is null, the parameter names are not returned and the signature could be simplified as "find(java.lang.String)".

      A cache mechanism is implemented, so you don't need to cache it again in the caller.

      Parameters:
      cls - the class to look
      signature - the method signature; the return type is optional
      Notice that the argument's type must be a full-qualified class name, unless its package is java.lang.
      params - the collection to hold the parameter names returned; null means no parameter names to return
      Throws:
      NoSuchMethodException
      ClassNotFoundException
    • getMethodInPublic

      public static final Method getMethodInPublic(Class<?> cls, String name, Class<?>[] argTypes) throws NoSuchMethodException
      Gets the method that is declared in a public class/interface.

      Class.getMethod returns a public method but the class itself might not be public. However, in many cases, that class also implements a public interface or class.

      This method will search all its public classes to look for the method that is 'real' public.

      If the public class found is in a package that its module does not export, such as sun.util.calendar, the same method declared by a public supertype in an exported package is returned instead, if any.

      NoSuchMethodException is thrown if no public class/interface is found to have the method.

      Throws:
      NoSuchMethodException
    • getMethodByObject

      public static final Method getMethodByObject(Class<?> cls, String name, Object[] args) throws NoSuchMethodException
      Gets one of the close method by specifying the arguments, rather than the argument types. It actually calls getCloseMethod(java.lang.Class<?>, java.lang.String, java.lang.Class<?>[]).
      Throws:
      NoSuchMethodException
    • getCloseMethod

      public static final Method getCloseMethod(Class<?> cls, String name, Class<?>[] argTypes) throws NoSuchMethodException
      Gets one of the close methods -- a close method is a method with the same name and the compatible argument type. By compatible we mean the real method's argument type is the same as or a superclass of the specified one.

      It might not be the best fit one, unless there is a method whose argument types are exactly argTypes.

      You might specify the exact number in argTypes. If any of them is unknown, use null. Example, in the following, the first argument could be anything and the second is anything deriving from MyClass:
      new Class[] {null, MyClass.class}

      Note: if an argument accepts int, then Integer is considered as compatible (unlike Class.getMethod). So are long, byte...

      A cache mechanism is implemented, so you don't need to cache it again in the caller.

      Parameters:
      cls - the class to locate the method
      name - the method name
      argTypes - an array of the argument classes; null to denote no argument at all (i.e., exact match). Any argTypes[i] could be null to denote any class.
      Returns:
      the method
      Throws:
      NoSuchMethodException - if the method is not found
    • getCloseMethodBySubclass

      public static final Method getCloseMethodBySubclass(Class<?> cls, String name, Class<?>[] argTypes) throws NoSuchMethodException
      Like getCloseMethod(java.lang.Class<?>, java.lang.String, java.lang.Class<?>[]) to get a 'close' method, but it look for subclass of the argument (instead of superclass). In other words, it looks for the method whose argument type is the same as or a subclass of the specified one.
      Throws:
      NoSuchMethodException
    • getCloseMethods

      public static final Method[] getCloseMethods(Class<?> cls, String name, Class<?>[] argTypes)
      Returns all close methods that match the specified condition, or a zero-length array if none is found.

      Unlike getCloseMethod(java.lang.Class<?>, java.lang.String, java.lang.Class<?>[]), we don't cache the searched result, and it won't throw any exception.

    • getCloseMethodsBySubclass

      public static final Method[] getCloseMethodsBySubclass(Class<?> cls, String name, Class<?>[] argTypes)
      Like getCloseMethods(java.lang.Class<?>, java.lang.String, java.lang.Class<?>[]) to get all 'close' methods, but it look for subclass of the argument (instead of superclass). In other words, it looks for the method whose argument type is the same as or a subclass of the specified one.
    • getAccessibleObject

      public static final AccessibleObject getAccessibleObject(Class<?> cls, String name, Class<?>[] argTypes, int flags) throws NoSuchMethodException
      Gets the specified accessible object, either a method or a field, by searching the specified name.

      The search sequence is: (assume field name is body)>
      getBody(...)
      isBody(...)
      body(...)
      body

      If B_SET is specified, setBody(...) is searched instead of getBody(...) and isBody(...). The field is searched only if argsType.length is 0 or 1.

      Note: it uses getCloseMethod(java.lang.Class<?>, java.lang.String, java.lang.Class<?>[]) to get the method.

      A cache mechanism is implemented, so you don't need to cache it again in the caller.

      Parameters:
      cls - the class to find
      name - the name of the accessible object
      argTypes - the parameter type of the method to find
      flags - a combination of B_xxx or zero
      Returns:
      the accessible object; either Field or Method
      Throws:
      NoSuchMethodException - if neither the set method of specified field nor the field itself not found
      SecurityException - if access to the information is denied
    • getAnyMethod

      public static final Method getAnyMethod(Class<?> cls, String name, Class<?>[] argTypes) throws NoSuchMethodException
      Gets the specified method by searching all methods including any access control and any base class. Note: you rarely need to call this method. In most cases, Class.getMethod, getCloseMethod(java.lang.Class<?>, java.lang.String, java.lang.Class<?>[]), and getMethodInPublic(java.lang.Class<?>, java.lang.String, java.lang.Class<?>[]) are what you need.

      The search sequence is: this class's methods, and then the superclass's methods.

      Note: public methods don't be treated different. If the caller wants to search public methods first, it has to call Class.getMethod first.

      Parameters:
      cls - the class to search
      name - the method name
      argTypes - the parameter array of types
      Returns:
      the Method object
      Throws:
      NoSuchMethodException - if a matching method is not found.
      SecurityException - if access to the information is denied.
      See Also:
    • getAnyField

      public static final Field getAnyField(Class<?> cls, String name) throws NoSuchFieldException
      Gets the specified field by searching all fields including any access control and any base class. The search sequence is: this class's fields, and then the superclass's fields.

      Note: public fields don't be treated different. If the caller wants to search public fields first, it has to call Class.getField first.

      Parameters:
      cls - the class to search
      name - the field name
      Returns:
      the Field object
      Throws:
      NoSuchFieldException - if a matching field is not found.
      SecurityException - if access to the information is denied.
      See Also:
    • getSuperClasses

      public static final Class<?>[] getSuperClasses(Class<?> cls, Class<?>[] clsToCheck)
      Searches thru each element of the specified array of classes, and returns classes that are super-classes (or equal) of the specified class.
      Parameters:
      cls - the specified class; null is not allowed
      clsToCheck - the class array to check; null is acceptable
      Returns:
      a subset of clsToCheck that are super-class of cls; null if no one qualified
    • isPrimitiveWrapper

      public static final boolean isPrimitiveWrapper(Class<?> cls)
      Check whether the specified class is a primitive or a primitive wrapper.
    • isNumeric

      public static final boolean isNumeric(Class<?> cls, boolean extend)
      Checks whether the specified class is a numeric class.
      Parameters:
      extend - whether to consider Date, char, boolean, Character and Boolean as a numeric object.
    • coerce

      public static Object coerce(Class<?> cls, Object val) throws ClassCastException
      Converts an object to the specified class. It is the same as coerce(cls, val, true).
      Parameters:
      val - the value.
      Throws:
      ClassCastException - if failed to convert
      See Also:
    • coerce

      public static Object coerce(Class<?> cls, Object val, boolean nullable) throws ClassCastException
      Converts to the specified type.
      Parameters:
      nullable - whether the result could be null. If false, 0 is used for number, the default constructor is used for others. coerce(Class, Object) is a special case that is equivalent to nullable=true.
      Throws:
      ClassCastException - if failed to convert
    • getContextClassLoader

      public static ClassLoader getContextClassLoader(Class<?> reference)
      Returns the context ClassLoader for the reference class.

      Default: return from the current thread.
      Or specify the library property of org.zkoss.lang.contextClassLoader.class in zk.xml to provide a customized class loader.

      Parameters:
      reference - the reference class where it is invoked from.
      Since:
      8.0.2
    • getContextClassLoaderForName

      public static ClassLoader getContextClassLoaderForName(String className)
      Returns the context ClassLoader for the given class name

      Default: return from the current thread.
      Or specify the library property of org.zkoss.lang.contextClassLoader.class in zk.xml to provide a customized class loader.

      Parameters:
      className - the class name to be loaded by the returned class loader
      Since:
      8.5.1
    • configureContextClassLoader

      public static void configureContextClassLoader()
      Sets the customized context ClassLoader name by the library property of org.zkoss.lang.contextClassLoader.class. It is intended to be called by ZK internally.
      Since:
      8.5.1