ClassInspector.java

Index Score
org.apache.derby.iapi.services.loader
Apache Derby

View: Reasons, Metrics, Source Code

These are the metrics that contribute to the Enerjy Score for this file, ranked by impact. So the metrics listed at the top influence the score to a greater extent that the metrics listed at the bottom.

MetricDescription
JAVA0034JAVA0034 Missing braces in if statement
LINE_COMMENTNumber of line comments
EXEC_COMMENTSComments in executable code
COMPARISONSNumber of comparison operators
CYCLOMATICCyclomatic complexity
SIZESize of the file in bytes
COMMENTSComment lines
LINESNumber of lines in the source file
RETURNSNumber of return points from functions
LOOPSNumber of loops
DOC_COMMENTNumber of javadoc comment lines
OPERATORSNumber of operators
INTERFACE_COMPLEXITYInterface complexity
PROGRAM_LENGTHHalstead program length
BLOCKSNumber of blocks
LOCLines of code
ELOCEffective lines of code
JAVA0049JAVA0049 Nested block at depth N (maximum: M)
JAVA0145JAVA0145 Tab character used in source file
OPERANDSNumber of operands
JAVA0177JAVA0177 Variable declaration missing initializer
LOGICAL_LINESNumber of statements
PARAMSNumber of formal parameter declarations
JAVA0108JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
UNIQUE_OPERANDSNumber of unique operands
PROGRAM_VOCABHalstead program vocabulary
WHITESPACENumber of whitespace lines
JAVA0030JAVA0030 Private field not used
JAVA0110JAVA0110 Incorrect javadoc: no @return tag
JAVA0115JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
EXITSProcedure exits
DECL_COMMENTSComments in declarations
JAVA0125JAVA0125 Continue statement with label
JAVA0270JAVA0270 Use Java 5.0 enhanced for loop construct to iterate over all elements in an array
NEST_DEPTHMaximum nesting depth
UNIQUE_OPERATORSNumber of unique operators
JAVA0076JAVA0076 Use of magic number
JAVA0117JAVA0117 Missing javadoc: method 'method'
JAVA0080JAVA0080 Import declaration not used
PROGRAM_VOLUMEHalstead program volume
JAVA0138JAVA0138 N parameters defined for method (maximum: M)
JAVA0126JAVA0126 Method declares unchecked exception in throws
JAVA0029JAVA0029 Private method not used
JAVA0009JAVA0009 Protected member in final class
/* Derby - Class org.apache.derby.iapi.services.loader.ClassInspector Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.derby.iapi.services.loader; import org.apache.derby.iapi.services.sanity.SanityManager; import org.apache.derby.iapi.error.StandardException; import org.apache.derby.iapi.reference.SQLState; import java.lang.reflect.*; import java.util.StringTokenizer; import java.util.List; import java.util.ArrayList; import java.util.NoSuchElementException; import java.util.Collections; /** Methods to find out relationships between classes and methods within a class. All class names within this interface are treated as java language class names, e.g. int, COM.foo.Myclass, int[], java.lang.Object[]. That is java internal class names as defined in the class file format are not understood. */ public final class ClassInspector { private static final String[] primTypeNames = {"boolean", "byte", "char", "short", "int", "long", "float", "double"}; // collect these as static, instead of each time allocates these new // Strings for every method resolution private static final String[] nonPrimTypeNames = {"java.lang.Boolean", "java.lang.Byte", "java.lang.Character", "java.lang.Short", "java.lang.Integer", "java.lang.Long", "java.lang.Float", "java.lang.Double"}; private static final String OBJECT_TYPE_NAME = "java.lang.Object"; private static final String STRING_TYPE_NAME = "java.lang.String"; private static final String BIGDECIMAL_TYPE_NAME = "java.math.BigDecimal"; private final ClassFactory cf; /** DO NOT USE! use the method in ClassFactory. */ public ClassInspector(ClassFactory cf) { this.cf = cf; } /** * Is the given object an instance of the named class? * * @param className The name of the class * @param obj The object to test to see if it's an instance * of the named class * * @return true if obj is an instanceof className, false if not */ public boolean instanceOf(String className, Object obj) throws ClassNotFoundException { Class clazz = getClass(className); // is className an untyped null if (clazz == null) return false; return clazz.isInstance(obj); } /** * Is one named class assignable to another named class or interface? * * @param fromClassName The name of the class to be assigned * @param toClassName The name of the class to be assigned to * * @return true if an object of type fromClass can be assigned to an * object of type toClass, false if not. */ public boolean assignableTo(String fromClassName, String toClassName) { try { Class toClass = getClass(toClassName); // is toClass an untyped null if (toClass == null) { return false; } Class fromClass = getClass(fromClassName); // is fromClass an untyped null if (fromClass == null) return !toClass.isPrimitive() || (toClass == Void.TYPE); return toClass.isAssignableFrom(fromClass); } catch (ClassNotFoundException cnfe) { /* If either class can't be found, they can't be assigned */ return false; } } /** * Does the named class exist, and is it accessible? * * @param className The name of the class to test for existence * * @return true if the class exists and is accessible, false if not */ public boolean accessible(String className) throws ClassNotFoundException { Class theClass = getClass(className); if (theClass == null) return false; /* Classes must be public to be accessible */ if (! Modifier.isPublic(theClass.getModifiers())) return false; return true; } /** * Get the Java name of the return type from a Member representing * a method or the type of a Member representing a field. * * @param member A Member representing the method for * which we want the return type. * * @return A Java-language-style string describing the return type of * the method (for example, it returns "int" instead of "I". */ public String getType(Member member) { Class type; if (member instanceof Method) type = ((Method) member).getReturnType(); else if (member instanceof Field) type = ((Field) member).getType(); else if (member instanceof Constructor) type = ((Constructor) member).getDeclaringClass(); else type = Void.TYPE; return ClassInspector.readableClassName(type); } /** * Find a public method that implements a given signature. * The signature is given using the full Java class names of the types. <BR> * A untyped null paramter is indicated by passing in an empty string ("") * as its class name. <BR> If receiverType respresents an interface then the methods of java.lang.Object arer included in the candidate list. <BR> If the caller is simply checking to see that a public method with the specified name exists, regardless of the signature, exists, then the caller should pass in a null for parmTypes. (This is useful for checking the validity of a method alias when creating one.) <BR> We use a two-pass algorithm to resolve methods. In the first pass, we use all "object" types to try to match a method. If this fails, in the second pass, an array of "primitive" types (if the parameter has one, otherwise the same object type is used) is passed in, as well as the "object" type array. For each parameter of a method, we try to match it against either the "object" type, or the "primitive" type. Of all the qualified candidate methods found, we choose the closest one to the input parameter types. This involves comparing methods whose parameters are mixed "object" and "primitive" types in the second pass. This is eventually handled in classConvertableFromTo. * * @param receiverType The class name of the receiver * @param methodName The name of the method * @param parmTypes An array of class names representing the * parameter types. Pass a zero-element array if * there are no parameters. Pass a null if it is * okay to match any signature. * @param primParmTypes This is used in the second pass of the two-pass * method resolution algorithm. Use primitive type * if it has one, otherwise use same object type * @param isParam Array of booleans telling whether parameter is a ?. * @param staticMethod Find a static method. @param repeatLastParameter If true the last parameter may be repeated any number of times (total count must be greater than one). If false the laste parameter is matched as usual. This also requires an exact match on the last parameter type. * * @return A Member representing the matching method. Returns null * if no such method. * * @exception ClassNotFoundException One or more of the classes does * not exist. * @exception StandardException Thrown on ambiguous method invocation. * * @see Member * @see Modifier */ public Member findPublicMethod(String receiverType, String methodName, String[] parmTypes, String[] primParmTypes, boolean[] isParam, boolean staticMethod, boolean repeatLastParameter) throws ClassNotFoundException, StandardException { Class receiverClass = getClass(receiverType); if (receiverClass == null) return null; // primitives don't have methods // note that arrays do since they are objects they have // all the methods of java.lang.Object if (receiverClass.isPrimitive()) { return null; } // if parmTypes is null, then the caller is simply // looking to see if any public method with the // specified name exists, regardless of its signature if (parmTypes == null) { Method[] methods = receiverClass.getMethods(); for (int index = 0; index < methods.length; index++) { if (staticMethod) { if (!Modifier.isStatic(methods[index].getModifiers())) { continue; } } if (methodName.equals(methods[index].getName())) { // We found a match return methods[index]; } } // No match return null; } // convert the parameter types to classes Class[] paramClasses = new Class[parmTypes.length]; Class[] primParamClasses = null; if (primParmTypes != null) primParamClasses = new Class[primParmTypes.length]; for (int i = 0; i < paramClasses.length; i++) { paramClasses[i] = getClass(parmTypes[i]); if (primParmTypes == null) continue; if (primParmTypes[i].equals(parmTypes[i])) // no separate primitive primParamClasses[i] = null; else primParamClasses[i] = getClass(primParmTypes[i]); } // no overloading possible if there are no arguments, so perform // an exact match lookup. if (paramClasses.length == 0) { try { Method method = receiverClass.getMethod(methodName, paramClasses); if (staticMethod) { if (!Modifier.isStatic(method.getModifiers())) return null; } return method; } catch (NoSuchMethodException nsme2) { // if we are an interface then the method could be defined on Object if (!receiverClass.isInterface()) return null; } } // now the tricky method resolution Member[] methodList = receiverClass.getMethods(); // if we have an interface we need to add the methods of Object into the mix if (receiverClass.isInterface()) { Member[] objectMethods = java.lang.Object.class.getMethods(); if (methodList.length == 0) { methodList = objectMethods; } else { Member[] set = new Member[methodList.length + objectMethods.length]; System.arraycopy(methodList, 0, set, 0, methodList.length); System.arraycopy(objectMethods, 0, set, methodList.length, objectMethods.length); methodList = set; } } return resolveMethod(receiverClass, methodName, paramClasses, primParamClasses, isParam, staticMethod, repeatLastParameter, methodList); } /** * Find a public field for a class. This follows the sematics of the java compiler for locating a field. This means if a field fieldName exists in the class with package, private or protected then an error is raised. Even if the field hides a field fieldName in a super-class/super--interface. See the JVM spec on fields. * * @param receiverType The class name of the receiver * @param fieldName The name of the field * @param staticField Find a static field * * @return A Member representing the matching field. * @exception StandardException Class or field does not exist or is not public or a security exception. * * @see Member * @see Modifier */ public Member findPublicField(String receiverType, String fieldName, boolean staticField) throws StandardException { Exception e = null; try { Class receiverClass = getClass(receiverType); if (receiverClass == null) return null; if (receiverClass.isArray() || receiverClass.isPrimitive()) { // arrays don't have fields (the fake field 'length' is not returned here) return null; } int modifier = staticField ? (Modifier.PUBLIC | Modifier.STATIC) : Modifier.PUBLIC; // Look for a public field first Field publicField = receiverClass.getField(fieldName); if ((publicField.getModifiers() & modifier) == modifier) { /* If the class is an interface then we avoid looking for a declared field that can hide a super-class's public field and not be accessable. This is because a interface's fields are always public. This avoids a security check. */ if (receiverClass.isInterface() || (publicField.getDeclaringClass().equals(receiverClass))) return publicField; /* Now check to see if there is a declared field that hides the public field. */ try { Field declaredField = receiverClass.getDeclaredField(fieldName); if (SanityManager.DEBUG) { if ((declaredField.getModifiers() & Modifier.PUBLIC) == Modifier.PUBLIC) SanityManager.THROWASSERT("declared field not expected to be public here " + declaredField); } } catch (NoSuchFieldException nsfe) { // no field hides the public field in the super class return publicField; } } } catch (ClassNotFoundException cnfe) { e = cnfe; } catch (NoSuchFieldException nsfep) { e = nsfep; } catch (SecurityException se) { e = se; } throw StandardException.newException( staticField ? SQLState.LANG_NO_STATIC_FIELD_FOUND : SQLState.LANG_NO_FIELD_FOUND, e, fieldName, receiverType); } /** * Find a public constructor that implements a given signature. * The signature is given using the full Java class names of the types. <BR> * A untyped null paramter is indicated by passing in an empty string ("") * as its class name. * * @param receiverType The class name of the receiver * @param parmTypes An array of class names representing the * parameter types. Pass a zero-element array if * there are no parameters. * @param primParmTypes This is used in the second pass of the two-pass * method resolution algorithm. Use primitive type * if it has one, otherwise use same object type * @param isParam Array of booleans telling whether parameter is a ?. * * @return A Member representing the matching constructor. Returns null * if no such constructor. * * @exception ClassNotFoundException One or more of the classes does * not exist. * @exception StandardException Thrown on ambiguous constructor invocation. * * @see Member * @see Modifier */ public Member findPublicConstructor(String receiverType, String[] parmTypes, String[] primParmTypes, boolean[] isParam) throws ClassNotFoundException, StandardException { Class receiverClass = getClass(receiverType); if (receiverClass == null) return null; // arrays, primitives, and interfaces do not have constructors if (receiverClass.isArray() || receiverClass.isPrimitive() || receiverClass.isInterface()) { return null; } // convert the parameter types to classes Class[] paramClasses = new Class[parmTypes.length]; Class[] primParamClasses = null; if (primParmTypes != null) primParamClasses = new Class[primParmTypes.length]; boolean unknownParameters = false; for (int i = 0; i < paramClasses.length; i++) { paramClasses[i] = getClass(parmTypes[i]); if (paramClasses[i] == null) unknownParameters = true; if (primParmTypes == null) continue; if (primParmTypes[i].equals(parmTypes[i])) // no separate primitive primParamClasses[i] = null; else primParamClasses[i] = getClass(primParmTypes[i]); } try { if (!unknownParameters && (primParmTypes == null)) { // look for an exact match for first pass Member method = receiverClass.getConstructor(paramClasses); return method; } } catch (NoSuchMethodException nsme) { // no overloading possible if there are no arguments if (paramClasses.length == 0) return null; // now the tricky method resolution } // name is only used for debugging return resolveMethod(receiverClass, "<init>", paramClasses, primParamClasses, isParam, false, false, receiverClass.getConstructors()); } /** * Get the parameter types for a method described by a Member as a String[]. * * @param method A Member describing a method * * @return A String[] describing the parameters of the method */ public String[] getParameterTypes(Member method) { Class[] parameterClasses; if (method instanceof Method) { parameterClasses = ((Method) method).getParameterTypes(); } else { parameterClasses = ((Constructor) method).getParameterTypes(); } String[] parameterTypes = new String[parameterClasses.length]; for (int i = 0; i < parameterTypes.length; i++) { parameterTypes[i] = ClassInspector.readableClassName(parameterClasses[i]); } return parameterTypes; } /** * Determine whether a type is a Java primitive, like int or boolean * * @param typeName The name of the Java type * * @return true if it's a primitive type */ public static boolean primitiveType(String typeName) { for (int i = 0; i < primTypeNames.length; i++) { if (typeName.equals(primTypeNames[i])) return true; } return false; } /** * Tricky function to resolve a method. If primParamClasses is null * we know it's first pass. First pass try to match as all "object" * types, second pass try to match any combination of "object" and * "primitive" types. Find the closest match among all the qualified * candidates. If there's a tie, it's ambiguous. * * The preceding paragraph is a bit misleading. As of release 10.4, the * second pass did not consider arbitrary combinations of primitive and * wrapper types. This is because the first pass removed from consideration * candidates which would be allowed under ANSI rules. As a fix for bug * DERBY-3652, we now allow primitive and wrapper type matches during * the first pass. The ANSI rules are documented in DERBY-3652. * * @param receiverClass the class who holds the methods * @param methodName the name of method * @param paramClasses object type classes of input parameters * @param primParamClasses primitive type classes or null * @param isParam isParam (for ?) array * @param staticMethod static method or not * @param methods method stack * @return the matched method * **/ private Member resolveMethod( Class receiverClass, String methodName, Class[] paramClasses, Class[] primParamClasses, boolean[] isParam, boolean staticMethod, boolean repeatLastParameter, Member[] methods) throws StandardException { if (SanityManager.DEBUG) { if (SanityManager.DEBUG_ON("MethodResolutionInfo")) { SanityManager.DEBUG("MethodResolutionInfo", "MRI - Begin method resolution trace for " + methodName + "() with " + paramClasses.length + (repeatLastParameter ? "+" : "") + " parameters"); for (int parmCtr = 0; parmCtr < paramClasses.length; parmCtr++) { SanityManager.DEBUG("MethodResolutionInfo", "MRI - Parameter #" + parmCtr + " is of type " + (paramClasses[parmCtr] == null ? "null" : paramClasses[parmCtr].getName())); } } } /* Step through all the methods available in this class */ int candidateIndex = -1; boolean firstTimeAround = true; boolean ambiguous; boolean somethingChanged; do { ambiguous = false; somethingChanged = false; nextMethod: for (int i = 0; i < methods.length; i++) { Member currentMethod = methods[i]; // on second and later times around there will be null entries // also, don't compare ourself to ourself if ((currentMethod == null) || (i == candidateIndex)) { continue; } // must have the same number of parameters Class[] currentMethodParameters = currentMethod instanceof Method ? ((Method) currentMethod).getParameterTypes(): ((Constructor) currentMethod).getParameterTypes(); // only check the basic stuff once if (firstTimeAround) { if (repeatLastParameter) { // match any number of parameters greater or equal to // the passed in number, but repeating the last type. if (currentMethodParameters.length < paramClasses.length) { methods[i] = null; // remove non-applicable methods continue; } } else { // regular match on parameter count if (currentMethodParameters.length != paramClasses.length) { methods[i] = null; // remove non-applicable methods continue; } } /* Look only at methods that match the modifiers */ if (staticMethod && !Modifier.isStatic(currentMethod.getModifiers())) { methods[i] = null; // remove non-applicable methods continue; } /* Look only at methods with the right name */ if (!methodName.startsWith("<")) { if ( ! methodName.equals(currentMethod.getName())) { methods[i] = null; // remove non-applicable methods continue; } } if (repeatLastParameter) { // With N parameters requested check all parameters from N-1 to end are equal // to the requested parameter. for (int pr = paramClasses.length - 1; pr < currentMethodParameters.length; pr++) { if (!currentMethodParameters[pr].equals(paramClasses[paramClasses.length - 1])) { methods[i] = null; // remove non-applicable methods continue nextMethod; } } } } if (SanityManager.DEBUG) { if (SanityManager.DEBUG_ON("MethodResolutionInfo")) { SanityManager.DEBUG("MethodResolutionInfo", "MRI - Considering :" + currentMethod.toString()); } } // // According to the ANSI rules, primitives and their // corresponding wrapper types are equally good for resolving // numeric arguments of user-coded functions and procedures. See // DERBY-3652 for a description of the ANSI rules. // // can the required signature be converted to those of this method? if (!signatureConvertableFromTo(paramClasses, primParamClasses, currentMethodParameters, isParam, true)) { if (SanityManager.DEBUG) { if (SanityManager.DEBUG_ON("MethodResolutionInfo")) { SanityManager.DEBUG("MethodResolutionInfo", "MRI - Skipping :" + currentMethod.toString()); } } methods[i] = null; // remove non-applicable methods continue; } if (SanityManager.DEBUG) { if (SanityManager.DEBUG_ON("MethodResolutionInfo")) { SanityManager.DEBUG("MethodResolutionInfo", "MRI - Match found "); } } /* Is this the first match? */ if (candidateIndex == -1) { candidateIndex = i; if (SanityManager.DEBUG) { if (SanityManager.DEBUG_ON("MethodResolutionInfo")) { SanityManager.DEBUG("MethodResolutionInfo", "MRI - Current method is now candidate"); } } continue; } // // Before the fixes to DERBY-3652, we used to weed out // ambiguities by applying the rules from section 15.11 // of the Java Language Specification. These are not the // ANSI resolution rules however. The code to weed out // ambiguities has been removed. // /* We have seen an ambiguous situation; one of the cases may * tie on each parameter. */ ambiguous = true; if (SanityManager.DEBUG) { if (SanityManager.DEBUG_ON("MethodResolutionInfo")) { SanityManager.DEBUG("MethodResolutionInfo", "MRI - Ambiguous match"); } } } firstTimeAround = false; } while (ambiguous && somethingChanged); if (SanityManager.DEBUG) { if (SanityManager.DEBUG_ON("MethodResolutionInfo")) { SanityManager.DEBUG("MethodResolutionInfo", "MRI - End method resolution trace for " + methodName + "()" + "\nMRI - "); } } /* Throw an exception here if the method invocation ambiguous */ if (ambiguous) { /* Put the parameter type names into a single string */ String parmTypesString = ""; for (int i = 0; i < paramClasses.length; i++) { if (i != 0) parmTypesString += ", "; parmTypesString += (paramClasses[i] == null ? "null" : paramClasses[i].getName()); if (primParamClasses != null && primParamClasses[i] != null) parmTypesString += "(" + primParamClasses[i].getName() + ")"; } throw StandardException.newException(SQLState.LANG_AMBIGUOUS_METHOD_INVOCATION, receiverClass.getName(), methodName, parmTypesString); } if (candidateIndex == -1) return null; if (SanityManager.DEBUG) { if (methods[candidateIndex] == null) SanityManager.THROWASSERT("methods is null at index " + candidateIndex); } return methods[candidateIndex]; } /** Get (load) the class for the given class name. This method converts any java language class name into a Class object. This includes cases like String[] and primitive types. This will attempt to load the class from the application set. @exception ClassNotFoundException Class cannot be found, or a SecurityException or LinkageException was thrown loading the class. */ public Class getClass(String className) throws ClassNotFoundException { if ((className == null) || (className.length() == 0)) { return null; } int arrayDepth = 0; int classNameLength = className.length(); int position = classNameLength - 2; while ((position >= 0) && className.substring(position, position + 2).equals("[]")) { arrayDepth++; position -= 2; classNameLength -= 2; } if (classNameLength <= 0) { // a bogus class name, let Class.forName deal with the error. return Class.forName(className); } if (arrayDepth != 0) className = className.substring(0, classNameLength); Class baseClass = null; if (classNameLength >=3 && classNameLength <=7) { if ("int".equals(className)) baseClass = Integer.TYPE; else if ("short".equals(className)) baseClass = Short.TYPE; else if ("boolean".equals(className)) baseClass = Boolean.TYPE; else if ("byte".equals(className)) baseClass = Byte.TYPE; else if ("float".equals(className)) baseClass = Float.TYPE; else if ("double".equals(className)) baseClass = Double.TYPE; else if ("long".equals(className)) baseClass = Long.TYPE; else if ("char".equals(className)) baseClass = Character.TYPE; else if ("void".equals(className)) baseClass = Void.TYPE; } if (baseClass == null) { baseClass = cf.loadApplicationClass(className); } if (arrayDepth == 0) return baseClass; // need to create an actual instance of the array type // and get its class from that. There is no other documented // way to do this. While a getName() on an array class // returns [[[Lclassname; format it's not consistent // with primitive types, e.g. // // Integer.TYPE.getName() returns "int" // Class.forName(new int[0] returns "[I" // if (arrayDepth == 1) return Array.newInstance(baseClass, 0).getClass(); return Array.newInstance(baseClass, new int[arrayDepth]).getClass(); } /** Is method/constructor T more or equally specific than method U. See the Java Language Specification section 15.11.2.2. */ private boolean isMethodMoreSpecificOrEqual(Member T, Member U, boolean[] isParam) { Class[] TC; Class[] UC; if (T instanceof Method) { if (!classConvertableFromTo(T.getDeclaringClass(), U.getDeclaringClass(), true)) return false; TC = ((Method) T).getParameterTypes(); UC = ((Method) U).getParameterTypes(); } else { TC = ((Constructor) T).getParameterTypes(); UC = ((Constructor) U).getParameterTypes(); } return signatureConvertableFromTo(TC, null, UC, isParam, true); } /** * Can we convert a signature from fromTypes(primFromTypes) to toTypes. * "mixTypes" is a flag to show if object/primitive type conversion is * possible; this is used for comparing two candidate methods in the * second pass of the two pass method resolution. * * @param fromTypes from types' classes * @param primFromTypes primitive from types or null * @param toTypes to types' classes * @param isParam is parameter (?) or not * @param mixTypes mixing object/primitive types for comparison **/ private boolean signatureConvertableFromTo(Class[] fromTypes, Class[] primFromTypes, Class[] toTypes, boolean[] isParam, boolean mixTypes) { // In the case repeatLastParameter was true, then the two methods may have // different numbers of parameters. We need to compare only the non-repeated // parameters, which is the number of input parameters. int checkCount = fromTypes.length; if (toTypes.length < checkCount) checkCount = toTypes.length; for (int i = 0; i < checkCount; i++) { Class fromClass = fromTypes[i]; Class toClass = toTypes[i]; // this means an untyped null was passed in. Can only ever be in the // from side as the null can only be in the signature passed in by // the caller of findPublicMethod. Any signatures of existing methods // are always typed. if (fromClass == null) { // primitive types are only considered on // the 2nd pass if (toClass.isPrimitive()) { if ((primFromTypes == null) // first pass || (isParam != null && ! isParam[i])) { return false; } } continue; } if ((!classConvertableFromTo(fromClass, toClass, mixTypes)) && // primitive type, if any, also doesn't work ((primFromTypes == null) || (primFromTypes[i] == null) || (!classConvertableFromTo(primFromTypes[i], toClass, mixTypes)) )) return false; } return true; } /** * Can we convert a fromClass to toClass. * "mixTypes" is a flag to show if object/primitive type conversion is * possible; this is used for comparing two candidate methods in the * second pass of the two pass method resolution. * * @param fromClass from class * @param toClass to class * @param mixTypes mixing object/primitive types for comparison **/ protected boolean classConvertableFromTo(Class fromClass, Class toClass, boolean mixTypes) { // // ANSI rules do not allow widening // if ( fromClass.getName().equals( toClass.getName() ) ) { return true; } // When comparing two candidate methods to see which one is closer, // we want to mix object type and primitive type, because they could // both be chosen in the second pass. But when deciding if a method // is qualified (to be a candidate), we do not want to mix types at // any time, the reason is that we can NOT do more than one step // conversion: for example, input parameter is BigDecimal, we convert // it to double for method resolution, we can NOT convert it again to // Double to match a method. "(paramTypes, primParamTypes)" already // includes all the one-step conversions. But at any time we do want // to see if two primitives are convertable. if ((!(toClass.isPrimitive() && fromClass.isPrimitive())) && (!mixTypes)) return false; // There are nine predefined Class objects to represent the eight // primitive Java types and void. We also handle prim vs. non-prim // conversion of the same type. boolean and double are only convertable // to themseleves. void should never be seen here. In the second pass // we treat primitive type and the corrsponding non-primitive type // uniformly String fromName = fromClass.getName(), toName = toClass.getName(); if ((fromClass == Boolean.TYPE) || fromName.equals(nonPrimTypeNames[0])) { if ((toClass == Boolean.TYPE) || toName.equals(nonPrimTypeNames[0])) return true; } else if ((fromClass == Byte.TYPE) || fromName.equals(nonPrimTypeNames[1])) { if ((toClass == Byte.TYPE) || toName.equals(nonPrimTypeNames[1]) || // we never need to see if toClass is of wider "object" type, // because a wider "object" type and a narrower "primitive" // type can never both be candidate, eg, "int" and "Long" can // never both accomodate the same parameter; while "long" and // "Integer" can. (toClass == Short.TYPE) || (toClass == Integer.TYPE) || (toClass == Long.TYPE) || (toClass == Float.TYPE) || (toClass == Double.TYPE) ) return true; } else if ((fromClass == Character.TYPE) || fromName.equals(nonPrimTypeNames[2])) { if ((toClass == Character.TYPE) || toName.equals(nonPrimTypeNames[2]) || (toClass == Integer.TYPE) || (toClass == Long.TYPE) || (toClass == Float.TYPE) || (toClass == Double.TYPE) ) return true; } else if ((fromClass == Short.TYPE) || fromName.equals(nonPrimTypeNames[3])) { if ((toClass == Short.TYPE) || toName.equals(nonPrimTypeNames[4]) ) return true; } else if ((fromClass == Integer.TYPE) || fromName.equals(nonPrimTypeNames[4])) { if ((toClass == Integer.TYPE) || toName.equals(nonPrimTypeNames[4]) ) return true; } else if ((fromClass == Long.TYPE) || fromName.equals(nonPrimTypeNames[5])) { if ((toClass == Long.TYPE) || toName.equals(nonPrimTypeNames[5]) ) return true; } else if ((fromClass == Float.TYPE) || fromName.equals(nonPrimTypeNames[6])) { if ((toClass == Float.TYPE) || toName.equals(nonPrimTypeNames[6]) ) return true; } else if ((fromClass == Double.TYPE) || fromName.equals(nonPrimTypeNames[7])) { if ((toClass == Double.TYPE) || toName.equals(nonPrimTypeNames[7])) return true; } return false; } /** * Translate a JVM-style type descriptor to a Java-language-style type * name. * * @param clazz The String that contains the JVM type name * * @return The Java-language-style type name */ public static String readableClassName(Class clazz) { if (!clazz.isArray()) return clazz.getName(); int arrayDepth = 0; do { arrayDepth++; clazz = clazz.getComponentType(); } while (clazz.isArray()); StringBuffer sb = new StringBuffer(clazz.getName()); for (int i = 0; i < arrayDepth; i++) { sb.append("[]"); } return sb.toString(); } /** * Determine whether or not the received class can be * loaded. * * @param className The name of the class in question * @return True if className can be loaded, false otherwise */ public static boolean classIsLoadable(String className) { try { Class.forName(className); return true; } catch (ClassNotFoundException ce) { return false; } catch (LinkageError ce) { return false; } } /** * Get the declaring class for a method. * * @param method A Member describing a method * * @return A String with the declaring class * * @see Member#getDeclaringClass */ public String getDeclaringClass(Member method) { return method.getDeclaringClass().getName(); } }

The table below shows all metrics for ClassInspector.java.

MetricValueDescription
BLOCKS112.00Number of blocks
BLOCK_COMMENT39.00Number of block comment lines
COMMENTS370.00Comment lines
COMMENT_DENSITY 0.84Comment density
COMPARISONS158.00Number of comparison operators
CYCLOMATIC192.00Cyclomatic complexity
DECL_COMMENTS21.00Comments in declarations
DOC_COMMENT236.00Number of javadoc comment lines
ELOC439.00Effective lines of code
EXEC_COMMENTS50.00Comments in executable code
EXITS53.00Procedure exits
FUNCTIONS18.00Number of function declarations
HALSTEAD_DIFFICULTY110.27Halstead difficulty
HALSTEAD_EFFORT 0.00Halstead effort
INTERFACE_COMPLEXITY129.00Interface complexity
JAVA0001 0.00JAVA0001 Package name does not contain only lower case letters
JAVA0002 0.00JAVA0002 Package name does not begin with a top level domain name or country code
JAVA0003 0.00JAVA0003 Minimize use of on-demand (.*) imports
JAVA0004 0.00JAVA0004 Unnecessary import from java.lang
JAVA0005 1.00JAVA0005 Imports not in specified order
JAVA0006 0.00JAVA0006 Empty finally block
JAVA0007 0.00JAVA0007 Should not declare public field
JAVA0008 0.00JAVA0008 Empty catch block
JAVA0009 1.00JAVA0009 Protected member in final class
JAVA0010 0.00JAVA0010 Non-instantiable class does not contain a non-private static member
JAVA0011 0.00JAVA0011 Abstract class does not contain an abstract method
JAVA0012 0.00JAVA0012 Non-constructor method with same name as declaring class
JAVA0013 0.00JAVA0013 Non-blank final field is not static
JAVA0014 0.00JAVA0014 Class with only static members has non-private constructor
JAVA0015 0.00JAVA0015 Package class contains public nested type
JAVA0016 0.00JAVA0016 Abstract class contains public constructor
JAVA0017 0.00JAVA0017 Class name does not have required form
JAVA0018 0.00JAVA0018 Method name does not have required form
JAVA0019 0.00JAVA0019 Interface name does not have required form
JAVA0020 0.00JAVA0020 Field name does not have required form
JAVA0021 0.00JAVA0021 Interface method name does not have required form
JAVA0022 0.00JAVA0022 Static final field name does not have required form
JAVA0023 0.00JAVA0023 Empty finalize method
JAVA0024 0.00JAVA0024 Empty class
JAVA0025 0.00JAVA0025 Method override is empty
JAVA0026 0.00JAVA0026 Finalize method with parameters
JAVA0029 1.00JAVA0029 Private method not used
JAVA0030 3.00JAVA0030 Private field not used
JAVA0031 0.00JAVA0031 Case statement not properly closed
JAVA0032 0.00JAVA0032 Switch statement missing default
JAVA0033 0.00JAVA0033 default: not last case in switch statement
JAVA003455.00JAVA0034 Missing braces in if statement
JAVA0035 0.00JAVA0035 Missing braces in for statement
JAVA0036 0.00JAVA0036 Missing braces in while statement
JAVA0038 0.00JAVA0038 Non-case label in switch statement
JAVA0039 0.00JAVA0039 Break statement with label
JAVA0040 0.00JAVA0040 Switch statement contains N cases (maximum: M)
JAVA0041 0.00JAVA0041 Nested synchronized block
JAVA0042 0.00JAVA0042 Empty synchronized statement
JAVA0043 0.00JAVA0043 Inner class does not use outer class
JAVA0044 0.00JAVA0044 Serializable class with no instance variables
JAVA0045 0.00JAVA0045 Serializable class with only transient fields
JAVA0046 0.00JAVA0046 Name of class not derived from Exception ends with 'Exception'
JAVA0047 0.00JAVA0047 Serializable class derives from invalid base class
JAVA0048 0.00JAVA0048 Name of class derived from Exception does not end with 'Exception'
JAVA0049 6.00JAVA0049 Nested block at depth N (maximum: M)
JAVA0050 0.00JAVA0050 Class derives from java.lang.Error
JAVA0051 0.00JAVA0051 Class derives from java.lang.RuntimeException
JAVA0052 0.00JAVA0052 Class derives from java.lang.Throwable
JAVA0053 0.00JAVA0053 Unused label
JAVA0054 0.00JAVA0054 Inheritance depth N exceeds maximum M
JAVA0055 0.00JAVA0055 Class should be interface
JAVA0056 0.00JAVA0056 Unnecessary abstract modifier for interface or annotation
JAVA0057 0.00JAVA0057 Unnecessary default constructor
JAVA0058 0.00JAVA0058 Constructor calls super()
JAVA0059 0.00JAVA0059 Method override only calls super()
JAVA0061 0.00JAVA0061 Inaccessible member in anonymous class
JAVA0062 0.00JAVA0062 Public class missing public member or protected constructor
JAVA0063 0.00JAVA0063 Identifier name should not contain '$'
JAVA0064 0.00JAVA0064 N variations of identifier name (maximum: M)
JAVA0065 0.00JAVA0065 Unnecessary final modifier for method in final class
JAVA0066 0.00JAVA0066 Unnecessary modifier for interface nested type
JAVA0067 0.00JAVA0067 Array descriptor on identifier name
JAVA0068 0.00JAVA0068 Modifiers not declared in recommended order
JAVA0071 0.00JAVA0071 Strings compared with ==
JAVA0073 0.00JAVA0073 Integer division in floating-point context
JAVA0074 0.00JAVA0074 Use of Object.notify()
JAVA0075 0.00JAVA0075 Method parameter hides field
JAVA0076 5.00JAVA0076 Use of magic number
JAVA0077 0.00JAVA0077 Private field not used in declaring class
JAVA0078 0.00JAVA0078 Floating point values compared with ==
JAVA0079 0.00JAVA0079 Use of instance to reference static member
JAVA0080 5.00JAVA0080 Import declaration not used
JAVA0081 0.00JAVA0081 Boolean literal in comparison
JAVA0082 0.00JAVA0082 Unnecessary widening cast
JAVA0083 0.00JAVA0083 Unnecessary instanceof test
JAVA0084 0.00JAVA0084 Should use compound assignment operator
JAVA0085 0.00JAVA0085 Use of sun.* class
JAVA0087 0.00JAVA0087 Use of Thread.sleep()
JAVA0089 0.00JAVA0089 Use of restricted package
JAVA0092 0.00JAVA0092 Use of restricted type
JAVA0093 0.00JAVA0093 Redundant assignment
JAVA0094 0.00JAVA0094 Field hides a superclass field
JAVA0095 0.00JAVA0095 Uninitialized private field
JAVA0096 0.00JAVA0096 Field in nested class hides outer field
JAVA0098 0.00JAVA0098 Minimize use of implicit field initializers
JAVA0100 0.00JAVA0100 Class contains N non-final fields (maximum: M)
JAVA0101 0.00JAVA0101 Unnecessary modifier for field in interface
JAVA0102 0.00JAVA0102 Last statement in finalize() not super.finalize()
JAVA0103 0.00JAVA0103 Explicit call to finalize()
JAVA0104 0.00JAVA0104 finalize() only calls super.finalize()
JAVA0105 0.00JAVA0105 Duplicate import declaration
JAVA0106 0.00JAVA0106 Unnecessary import from current package
JAVA0108 6.00JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
JAVA0109 0.00JAVA0109 Incorrect javadoc: no parameter 'parameter'
JAVA0110 4.00JAVA0110 Incorrect javadoc: no @return tag
JAVA0111 0.00JAVA0111 Incorrect javadoc: @return tag for void method
JAVA0112 0.00JAVA0112 Incorrect javadoc: no exception 'exception' in throws
JAVA0113 1.00JAVA0113 Incorrect javadoc: no @author tag
JAVA0114 1.00JAVA0114 Incorrect javadoc: no @version tag
JAVA0115 3.00JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
JAVA0116 0.00JAVA0116 Missing javadoc: field 'field'
JAVA0117 0.00JAVA0117 Missing javadoc: method 'method'
JAVA0118 0.00JAVA0118 Missing javadoc: type 'type'
JAVA0119 0.00JAVA0119 Control variable changed within body of for loop
JAVA0123 0.00JAVA0123 Use all three components of for loop
JAVA0125 1.00JAVA0125 Continue statement with label
JAVA0126 0.00JAVA0126 Method declares unchecked exception in throws
JAVA0128 0.00JAVA0128 Public constructor in non-public class
JAVA0130 0.00JAVA0130 Non-static method does not use instance fields
JAVA0131 0.00JAVA0131 Compatible method does not override base
JAVA0132 0.00JAVA0132 Method overload with compatible signature
JAVA0133 0.00JAVA0133 Non-synchronized method overrides synchronized method
JAVA0135 0.00JAVA0135 Only one of Object.equals and Object.hashCode defined: missing 'method'
JAVA0136 0.00JAVA0136 N methods defined in class (maximum: M)
JAVA0137 0.00JAVA0137 Non-abstract class missing constructor
JAVA0138 2.00JAVA0138 N parameters defined for method (maximum: M)
JAVA0139 0.00JAVA0139 Definition of main other than public static void main(java.lang.String[])
JAVA0141 0.00JAVA0141 Unnecessary modifier for method in interface
JAVA0143 0.00JAVA0143 Synchronized method
JAVA0144 1.00JAVA0144 Line exceeds maximum M characters
JAVA01452552.00JAVA0145 Tab character used in source file
JAVA0150 0.00JAVA0150 java.lang.Error (or subclass) thrown
JAVA0153 0.00JAVA0153 Inefficient conversion of integer to string
JAVA0159 0.00JAVA0159 Inefficient conversion of string to integer
JAVA0160 0.00JAVA0160 Method does not throw specified exception
JAVA0161 0.00JAVA0161 Conditional wait() not in loop
JAVA0163 0.00JAVA0163 Empty statement
JAVA0165 0.00JAVA0165 Conflicting return statement in finally block
JAVA0166 0.00JAVA0166 Generic exception caught
JAVA0167 0.00JAVA0167 ThreadDeath not rethrown
JAVA0169 0.00JAVA0169 Unnecessary catch block: exception 'exception'
JAVA0170 1.00JAVA0170 Caught exception not derived from java.lang.Exception
JAVA0171 0.00JAVA0171 Unused local variable
JAVA0173 0.00JAVA0173 Unused method parameter
JAVA0174 0.00JAVA0174 Assigned local variable never used
JAVA0175 0.00JAVA0175 Successive assignment to variable
JAVA0176 0.00JAVA0176 Local variable name does not have required form
JAVA0177 6.00JAVA0177 Variable declaration missing initializer
JAVA0179 0.00JAVA0179 Local variable hides visible field
JAVA0233 0.00JAVA0233 Definition of serialVersionUID other than 'private static final long serialVersionUID'
JAVA0234 0.00JAVA0234 Class is Serializable but does not define serialVersionUID
JAVA0235 0.00JAVA0235 Class defines serialVersionUID but does not implement Serializable
JAVA0236 0.00JAVA0236 Attempt to clone an object which does not implement Cloneable
JAVA0237 0.00JAVA0237 Class implements Cloneable but does not have public clone method
JAVA0238 0.00JAVA0238 Clone method does not call super.clone()
JAVA0239 0.00JAVA0239 Class declares 'readObject' or 'writeObject' but does not implement Serializable
JAVA0240 0.00JAVA0240 Serializable class which declares readObject or writeObject but not both
JAVA0241 0.00JAVA0241 'readObject' or 'writeObject' should be declared private in Serializable class
JAVA0242 0.00JAVA0242 Transient field in non-Serializable class
JAVA0243 0.00JAVA0243 'readResolve' or 'writeReplace' should be declared private or protected
JAVA0244 0.00JAVA0244 Field or method name in subclass differs only by case from inherited field or method
JAVA0245 0.00JAVA0245 JUnit TestCase with non-trivial constructor
JAVA0246 0.00JAVA0246 JUnit assertXXX statement missing message parameter
JAVA0247 0.00JAVA0247 JUnit 'setUp()' and 'tearDown()' should call super method
JAVA0248 0.00JAVA0248 JUnit method 'setUp' or 'tearDown' with incorrect signature
JAVA0249 0.00JAVA0249 JUnit TestCase 'suite()' should be declared static
JAVA0250 0.00JAVA0250 JUnit TestCase declares testXXX method with incorrect signature
JAVA0251 0.00JAVA0251 Use '%n' for line breaks in printf/format for platform independence
JAVA0252 0.00JAVA0252 'enum' is a Java 1.5 reserved word
JAVA0253 0.00JAVA0253 Not all enum constants consumed in switch statement
JAVA0254 0.00JAVA0254 Use enhanced for loop construct instead of Iterator
JAVA0255 0.00JAVA0255 Result of method invocation not used
JAVA0256 0.00JAVA0256 Assignment of external collection/array to field
JAVA0257 0.00JAVA0257 Use of 'Constant Interface' anti-pattern
JAVA0258 0.00JAVA0258 Implement Iterable for foreach compatibility
JAVA0259 0.00JAVA0259 Return of collection/array field
JAVA0260 0.00JAVA0260 Use 'enum' instead of Enumerated Type pattern
JAVA0261 0.00JAVA0261 Use specialized Enum collection types
JAVA0262 0.00JAVA0262 Use of char in integer context
JAVA0263 0.00JAVA0263 Long literal ends with 'l' instead of 'L'
JAVA0264 0.00JAVA0264 Integer math in long context - check for overflow
JAVA0265 0.00JAVA0265 Use of Throwable.printStackTrace()
JAVA0266 0.00JAVA0266 Use of System.out
JAVA0267 0.00JAVA0267 Use of System.err
JAVA0269 0.00JAVA0269 Contents of StringBuffer never used
JAVA0270 2.00JAVA0270 Use Java 5.0 enhanced for loop construct to iterate over all elements in an array
JAVA0271 0.00JAVA0271 Minimize use of on-demand (.*) static imports
JAVA0272 0.00JAVA0272 Thread.run() called
JAVA0273 0.00JAVA0273 Non-final derivative of Thread calls start() in constructor
JAVA0274 0.00JAVA0274 Serializable class has a synchronized readObject()
JAVA0275 0.00JAVA0275 Serializable class has a synchronized writeObject() and no other synchronized methods
JAVA0276 0.00JAVA0276 Unnecessary use of String constructor
JAVA0277 0.00JAVA0277 Iterator.next() implementation does not throw NoSuchElementException
JAVA0278 0.00JAVA0278 Unnecessary use of Boolean constructor
JAVA0279 0.00JAVA0279 Serialization method readObject or readObjectNoData calls an overridable method
JAVA0280 0.00JAVA0280 IllegalMonitorStateException caught
JAVA0281 0.00JAVA0281 Iterator.next() not called in loop
JAVA0282 0.00JAVA0282 Call to Iterator.next() in loop which does not test Iterator.hasNext()
JAVA0283 0.00JAVA0283 Control variable not updated in loop body
JAVA0284 0.00JAVA0284 Explicit garbage collection
JAVA0285 0.00JAVA0285 Dereference of potentially null variable
JAVA0286 0.00JAVA0286 Dereference of null variable
JAVA0287 0.00JAVA0287 Unnecessary null check
JAVA0288 0.00JAVA0288 Inconsistent null check
LINES1092.00Number of lines in the source file
LINE_COMMENT95.00Number of line comments
LOC566.00Lines of code
LOGICAL_LINES228.00Number of statements
LOOPS14.00Number of loops
NEST_DEPTH 7.00Maximum nesting depth
OPERANDS1207.00Number of operands
OPERATORS2534.00Number of operators
PARAMS46.00Number of formal parameter declarations
PROGRAM_LENGTH3741.00Halstead program length
PROGRAM_VOCAB356.00Halstead program vocabulary
PROGRAM_VOLUME 0.00Halstead program volume
RETURNS83.00Number of return points from functions
SIZE34853.00Size of the file in bytes
UNIQUE_OPERANDS301.00Number of unique operands
UNIQUE_OPERATORS55.00Number of unique operators
WHITESPACE156.00Number of whitespace lines