?? classes.java
字號(hào):
/* Classes.java{{IS_NOTE Purpose: Utilities to handle Class Description: History: 2001/4/19, Tom M. Yeh: Created.}}IS_NOTECopyright (C) 2001 Potix Corporation. All Rights Reserved.{{IS_RIGHT This program is distributed under GPL Version 2.0 in the hope that it will be useful, but WITHOUT ANY WARRANTY.}}IS_RIGHT*/package org.zkoss.lang;import java.util.Map;import java.util.HashMap;import java.util.List;import java.util.LinkedList;import java.util.Collection;import java.util.Arrays;import java.util.Date;import java.lang.reflect.Constructor;import java.lang.reflect.AccessibleObject;import java.lang.reflect.Method;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Modifier;import java.math.BigDecimal;import java.math.BigInteger;import org.zkoss.mesg.MCommon;import org.zkoss.mesg.Messages;import org.zkoss.lang.Strings;import org.zkoss.lang.Objects;import org.zkoss.math.BigDecimals;import org.zkoss.math.BigIntegers;import org.zkoss.util.MultiCache;import org.zkoss.util.Cache;import org.zkoss.util.IllegalSyntaxException;import org.zkoss.util.logging.Log;/** * Utilities to handle java.lang.Class * * @author tomyeh */public class Classes { private static final Log log = Log.lookup(Classes.class); /** * Creates and intializes a new instance of the specified class with * the specified arguments. * * <p>Note only public constructors are searched. * * @param cls the class of the instance to create * @param argTypes the argument types of the constructor to inovke * @param args the arguments to initialize the instance * @return the new instance * * @exception NoSuchMethodException if a matching method is not found * @exception InstantiationException if the class that declares the * underlying constructor represents an abstract class * @exception InvocationTargetException if the underlying constructor * throws an exception * @see #newInstance(String, Class[], Object[]) */ public static final Object newInstance(Class cls, Class[] argTypes, Object[] args) throws NoSuchMethodException, InstantiationException, InvocationTargetException { Constructor contr = cls.getConstructor(argTypes); try { return contr.newInstance(args); } catch (IllegalAccessException ex) { throw SystemException.Aide.wrap(ex); } } /** * Creates and initializes a new instance of the specified class name * with the specified arguments. * * <p>It uses Class.forName to get the class. * * @param clsName the class name of the instance to create * @param argTypes the argument types of the constructor to inovke * @param args the arguments to initialize the instance * @return the new instance * * @exception NoSuchMethodException if a matching method is not found * @exception InstantiationException if the class that declares the * underlying constructor represents an abstract class * @exception InvocationTargetException if the underlying constructor * throws an exception * @exception ClassNotFoundException if the specified class name is not a class * @see #newInstance(Class, Class[], Object[]) */ public static final Object newInstance(String clsName, Class[] argTypes, Object[] args) throws NoSuchMethodException, InstantiationException, InvocationTargetException, ClassNotFoundException { return newInstance(Class.forName(clsName), argTypes, args); } /** * Creates and initializes a new instance of the specified class name * with the specified arguments, by use of {@link #forNameByThread}. * * <p>It uses {@link #forNameByThread} to get the class. * * @param clsName the class name of the instance to create * @param argTypes the argument types of the constructor to inovke * @param args the arguments to initialize the instance * @return the new instance * * @exception NoSuchMethodException if a matching method is not found * @exception InstantiationException if the class that declares the * underlying constructor represents an abstract class * @exception InvocationTargetException if the underlying constructor * throws an exception * @exception ClassNotFoundException if the specified class name is not a class * @see #newInstance(Class, Class[], Object[]) */ public static final Object newInstanceByThread(String clsName, Class[] argTypes, Object[] args) throws NoSuchMethodException, InstantiationException, InvocationTargetException, ClassNotFoundException { return newInstance(forNameByThread(clsName), argTypes, args); } /** * Creates and initializes a new instance of the specified class name * with default constructor, by use of {@link #forNameByThread}. */ public static final Object newInstanceByThread(String clsName) throws NoSuchMethodException, InstantiationException, InvocationTargetException, ClassNotFoundException { return newInstance(forNameByThread(clsName), null, null); } /** * Returns the Class object of the specified class name, using * the current thread's context class loader. * * <p>In additions, it handles the primitive types, such as int and double. * * @param clsName fully qualified name of the desired class * @return the Class object representing the desired class * @exception ClassNotFoundException if the class cannot be located by the specified class loader */ public static final Class forNameByThread(String clsName) throws ClassNotFoundException { clsName = toInternalForm(clsName); final Class cls = Primitives.toClass(clsName); return cls != null ? cls: Class.forName(clsName, true, Thread.currentThread().getContextClassLoader()); } /** * Change class name to internal form (e.g. byte[] -> [B). If already in * internal form, then just return it. */ public static final String toInternalForm(String clsName) { final int k = clsName.indexOf('['); if (k <= 0) { //not an array, or already in internal form return clsName; //just return } //component class final String elm = clsName.substring(0, k).trim(); if (elm.length() == 0) throw new IllegalArgumentException("Not a legal class name: \""+clsName+'"'); //array depth boolean leftb = false; final String stub = clsName.substring(k); final StringBuffer sb = new StringBuffer(128); for (int j = 0; j < stub.length(); j++) { final char ch = stub.charAt(j); if (ch == '[') { if (leftb) throw new IllegalArgumentException("Not a legal class name: \""+clsName+'"'); leftb = true; sb.append('['); } else if (ch == ']') { if (!leftb) throw new IllegalArgumentException("Not a legal class name: \""+clsName+'"'); leftb = false; } } if (leftb) throw new IllegalArgumentException("Not a legal class name: \""+clsName+'"'); final char code = Primitives.getNotation(elm); if (code != (char)0) {//primitive array sb.append(code); } else {//object array sb.append('L').append(elm).append(';'); } return sb.toString(); } /** * 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. * * <p>The interfaces implemented by the specified class is checked first, * and then the subclass. * * @param cls the class or interface * @param subIF the sub-interface * @return the topmost interface extending subIF, or null if subIF * is not implemented by cls */ public static Class getTopmostInterface(Class cls, Class subIF) { if (cls.isInterface()) return subIF.isAssignableFrom(cls) ? cls: null; while (cls != null) { final Class[] ifs = cls.getInterfaces(); for (int j = 0; j < ifs.length; ++j) if (subIF.isAssignableFrom(ifs[j])) return ifs[j]; cls = cls.getSuperclass(); } return null; } /** Returns all interfaces that are implemented by the specified class. * <p>Unlike {@link Class#getInterfaces}, it recursively searches * for all derived classes. */ public static Class[] getAllInterfaces(Class cls) { final List l = new LinkedList(); while (cls != null) { final Class[] ifs = cls.getInterfaces(); for (int j = 0; j < ifs.length; ++j) l.add(ifs[j]); cls = cls.getSuperclass(); } final int sz = l.size(); return (Class[])l.toArray(new Class[sz]); } /** * Tests whether a class contains the specified method. * Only public methods are tested. * * @param cls the class to test * @param name the method name * @param paramTypes the list of parameter types * @return true if it contains the method */ public static final boolean containsMethod (Class cls, String name, Class[] paramTypes) { try { cls.getMethod(name, paramTypes); return true; } catch (NoSuchMethodException ex) {//no found return false; } } /** Corrects a string to a valid Java name. * Currently, it only removes '-' and capitalizes the succeeding * character. Example, 'field-name' becomes 'fieldName'. */ public final static String correctFieldName(String name) { int j = name.indexOf('-'); if (j < 0) return name; //nothing to change for (final StringBuffer sb = new StringBuffer(name);;) { sb.deleteCharAt(j); if (sb.length() == j) return sb.toString(); sb.setCharAt(j, Character.toUpperCase(sb.charAt(j))); j = sb.indexOf("-", j); if (j < 0) return sb.toString(); } } /** * Convert an attribute name, returned by toAttributeName, to * a method name. * * <p>toMethodName("true", "is") => "isTrue"<br> * toMethodName("true", "") => "true" * * @param attrName the attribute name * @param prefix the prefix; one of is, get and set * @return the method name * @see #toAttributeName */ public static final String toMethodName(String attrName, String prefix) { if (prefix.length() == 0) return attrName; StringBuffer sb = new StringBuffer(prefix); char[] buf = attrName.toCharArray(); buf[0] = Character.toUpperCase(buf[0]); return sb.append(buf).toString(); } /** * 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'. * * <p>Note 'set' is considered as an attribute, whose name is an * empty string. * * @param methodName the method name to test * @return true if it is setter or getter */ public static final boolean isAttribute(String methodName) { int len = methodName.length(); if (len < 2) return false; int j; switch (methodName.charAt(0)) { case 's': case 'g': if (len<3 || methodName.charAt(1)!='e' || methodName.charAt(2)!='t') return false; j = 3; break; case 'i': if (methodName.charAt(1)!='s') return false; j = 2; break; default: return false; } return j==len || Character.isUpperCase(methodName.charAt(j)); } /** * 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. * * <p>The code is optimized for better performance. * * @param methodName the method name * @return the attribute name; null if it is not an attribute name * @see #toMethodName */ public static final String toAttributeName(String methodName) { int len = methodName.length(); if (len < 2) return null; int j; switch (methodName.charAt(0)) { case 's': case 'g': if (len<3 || methodName.charAt(1)!='e' || methodName.charAt(2)!='t') return null; j = 3; break; case 'i': if (methodName.charAt(1)!='s') return null; j = 2; break; default: return null; } if (j==len || Character.isUpperCase(methodName.charAt(j))) { char[] buf = new char[len - j]; if (buf.length>0) { methodName.getChars(j, len, buf, 0); buf[0] = Character.toLowerCase(buf[0]); } return new String(buf); } return null; } //--Support Class-- /**The method info class used for {@link #parseMethod(String signature)}. * This info describe the method return type, method name and two collections for * arguments type and arguments name; */ public static class MethodInfo { /** The return type (class name), or null if no specified. */ public String returnType; public String method; public String[] argTypes; public String[] argNames; public String throwsEx; //constructor protected MethodInfo(String r, String m, String[] argTs, String[] argNs, String tEx) { returnType = r; method = m; argTypes = argTs; argNames = argNs; throwsEx = tEx; } } /** * 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. * * @param signature the method signature. * @return MethodInfo The method information including return type, method name * and two collections for argument type annd arguments name. */ public static final MethodInfo parseMethod(String signature) throws IllegalSyntaxException { int len = signature.length(); int j = Strings.skipWhitespaces(signature, 0); int k = Strings.anyOf(signature, "( \t\n\r", j); k = Strings.skipWhitespaces(signature, k); if (k >= len) throw new IllegalSyntaxException(signature); String returnType = null;
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -