GrailsClassUtils.java

Index Score
org.codehaus.groovy.grails.commons
Grails

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
COMPARISONSNumber of comparison operators
RETURNSNumber of return points from functions
INTERFACE_COMPLEXITYInterface complexity
CYCLOMATICCyclomatic complexity
DOC_COMMENTNumber of javadoc comment lines
DECL_COMMENTSComments in declarations
SIZESize of the file in bytes
BLOCKSNumber of blocks
PARAMSNumber of formal parameter declarations
EXITSProcedure exits
COMMENTSComment lines
LINESNumber of lines in the source file
OPERATORSNumber of operators
PROGRAM_LENGTHHalstead program length
LOCLines of code
OPERANDSNumber of operands
UNIQUE_OPERANDSNumber of unique operands
JAVA0166JAVA0166 Generic exception caught
FUNCTIONSNumber of function declarations
PROGRAM_VOCABHalstead program vocabulary
JAVA0270JAVA0270 Use Java 5.0 enhanced for loop construct to iterate over all elements in an array
ELOCEffective lines of code
LOGICAL_LINESNumber of statements
EXEC_COMMENTSComments in executable code
JAVA0177JAVA0177 Variable declaration missing initializer
LOOPSNumber of loops
UNIQUE_OPERATORSNumber of unique operators
JAVA0144JAVA0144 Line exceeds maximum M characters
JAVA0008JAVA0008 Empty catch block
PROGRAM_VOLUMEHalstead program volume
JAVA0136JAVA0136 N methods defined in class (maximum: M)
LINE_COMMENTNumber of line comments
JAVA0110JAVA0110 Incorrect javadoc: no @return tag
JAVA0173JAVA0173 Unused method parameter
NEST_DEPTHMaximum nesting depth
JAVA0108JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
/* Copyright 2004-2005 the original author or authors. * * Licensed 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.codehaus.groovy.grails.commons; import groovy.lang.*; import org.apache.commons.lang.StringUtils; import org.springframework.beans.*; import org.springframework.util.Assert; import org.springframework.core.JdkVersion; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.*; /** * @author Graeme Rocher * @since 08-Jul-2005 * * Class containing utility methods for dealing with Grails class artifacts * */ public class GrailsClassUtils { private static final String PROPERTY_SET_PREFIX = "set"; public static final Map PRIMITIVE_TYPE_COMPATIBLE_CLASSES = new HashMap(); /** * Just add two entries to the class compatibility map * @param left * @param right */ private static final void registerPrimitiveClassPair(Class left, Class right) { PRIMITIVE_TYPE_COMPATIBLE_CLASSES.put( left, right); PRIMITIVE_TYPE_COMPATIBLE_CLASSES.put( right, left); } static { registerPrimitiveClassPair( Boolean.class, boolean.class); registerPrimitiveClassPair( Integer.class, int.class); registerPrimitiveClassPair( Short.class, short.class); registerPrimitiveClassPair( Byte.class, byte.class); registerPrimitiveClassPair( Character.class, char.class); registerPrimitiveClassPair( Long.class, long.class); registerPrimitiveClassPair( Float.class, float.class); registerPrimitiveClassPair( Double.class, double.class); } /** * * Returns true if the specified property in the specified class is of the specified type * * @param clazz The class which contains the property * @param propertyName The property name * @param type The type to check * * @return A boolean value */ public static boolean isPropertyOfType( Class clazz, String propertyName, Class type ) { try { Class propType = getPropertyType( clazz, propertyName ); return propType != null && propType.equals(type); } catch(Exception e) { return false; } } /** * Returns the value of the specified property and type from an instance of the specified Grails class * * @param clazz The name of the class which contains the property * @param propertyName The property name * @param propertyType The property type * * @return The value of the property or null if none exists */ public static Object getPropertyValueOfNewInstance(Class clazz, String propertyName, Class propertyType) { // validate if(clazz == null || StringUtils.isBlank(propertyName)) return null; Object instance = null; try { instance = BeanUtils.instantiateClass(clazz); } catch (BeanInstantiationException e) { return null; } return getPropertyOrStaticPropertyOrFieldValue(instance, propertyName); } /** * Returns the value of the specified property and type from an instance of the specified Grails class * * @param clazz The name of the class which contains the property * @param propertyName The property name * * @return The value of the property or null if none exists */ public static Object getPropertyValueOfNewInstance(Class clazz, String propertyName) { // validate if(clazz == null || StringUtils.isBlank(propertyName)) return null; Object instance = null; try { instance = BeanUtils.instantiateClass(clazz); } catch (BeanInstantiationException e) { return null; } return getPropertyOrStaticPropertyOrFieldValue(instance, propertyName); } /** * Retrieves a PropertyDescriptor for the specified instance and property value * * @param instance The instance * @param propertyValue The value of the property * @return The PropertyDescriptor */ public static PropertyDescriptor getPropertyDescriptorForValue(Object instance, Object propertyValue) { if(instance == null || propertyValue == null) return null; BeanWrapper wrapper = new BeanWrapperImpl(instance); PropertyDescriptor[] descriptors = wrapper.getPropertyDescriptors(); for (int i = 0; i < descriptors.length; i++) { Object value = wrapper.getPropertyValue( descriptors[i].getName() ); if(propertyValue.equals(value)) return descriptors[i]; } return null; } /** * Returns the type of the given property contained within the specified class * * @param clazz The class which contains the property * @param propertyName The name of the property * * @return The property type or null if none exists */ public static Class getPropertyType(Class clazz, String propertyName) { if(clazz == null || StringUtils.isBlank(propertyName)) return null; try { BeanWrapper wrapper = new BeanWrapperImpl(clazz); if(wrapper.isReadableProperty(propertyName)) { return wrapper.getPropertyType(propertyName); } else { return null; } } catch (Exception e) { // if there are any errors in instantiating just return null for the moment return null; } } /** * Retrieves all the properties of the given class for the given type * * @param clazz The class to retrieve the properties from * @param propertyType The type of the properties you wish to retrieve * * @return An array of PropertyDescriptor instances */ public static PropertyDescriptor[] getPropertiesOfType(Class clazz, Class propertyType) { if(clazz == null || propertyType == null) return new PropertyDescriptor[0]; Set properties = new HashSet(); try { BeanWrapper wrapper = new BeanWrapperImpl(clazz.newInstance()); PropertyDescriptor[] descriptors = wrapper.getPropertyDescriptors(); for (int i = 0; i < descriptors.length; i++) { Class currentPropertyType = descriptors[i].getPropertyType(); if(isTypeInstanceOfPropertyType(propertyType, currentPropertyType)) { properties.add(descriptors[i]); } } } catch (Exception e) { // if there are any errors in instantiating just return null for the moment return new PropertyDescriptor[0]; } return (PropertyDescriptor[])properties.toArray( new PropertyDescriptor[ properties.size() ] ); } private static boolean isTypeInstanceOfPropertyType(Class type, Class propertyType) { return propertyType.isAssignableFrom(type) && !propertyType.equals(Object.class); } /** * Retrieves all the properties of the given class which are assignable to the given type * * @param clazz The class to retrieve the properties from * @param propertySuperType The type of the properties you wish to retrieve * @return An array of PropertyDescriptor instances */ public static PropertyDescriptor[] getPropertiesAssignableToType(Class clazz, Class propertySuperType) { if (clazz == null || propertySuperType == null) return new PropertyDescriptor[0]; Set properties = new HashSet(); try { PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(clazz); for (int i = 0; i < descriptors.length; i++) { if (propertySuperType.isAssignableFrom(descriptors[i].getPropertyType())) { properties.add(descriptors[i]); } } } catch (Exception e) { return new PropertyDescriptor[0]; } return (PropertyDescriptor[]) properties.toArray(new PropertyDescriptor[properties.size()]); } /** * Retrieves a property of the given class of the specified name and type * @param clazz The class to retrieve the property from * @param propertyName The name of the property * @param propertyType The type of the property * * @return A PropertyDescriptor instance or null if none exists */ public static PropertyDescriptor getProperty(Class clazz, String propertyName, Class propertyType) { if(clazz == null || propertyName == null || propertyType == null) return null; try { BeanWrapper wrapper = new BeanWrapperImpl(clazz.newInstance()); PropertyDescriptor pd = wrapper.getPropertyDescriptor(propertyName); if(pd.getPropertyType().equals( propertyType )) { return pd; } else { return null; } } catch (Exception e) { // if there are any errors in instantiating just return null for the moment return null; } } /** * Returns the class name without the package prefix * * @param targetClass The class to get a short name for * @return The short name of the class */ public static String getShortName(Class targetClass) { String className = targetClass.getName(); return getShortName(className); } /** * Returns the class name without the package prefix * * @param className The class name to get a short name for * @return The short name of the class */ public static String getShortName(String className) { int i = className.lastIndexOf("."); if(i > -1) { className = className.substring( i + 1, className.length() ); } return className; } /** * Returns the property name equivalent for the specified class * * @param targetClass The class to get the property name for * @return A property name reperesentation of the class name (eg. MyClass becomes myClass) */ public static String getPropertyNameRepresentation(Class targetClass) { String shortName = getShortName(targetClass); return getPropertyNameRepresentation(shortName); } /** * Returns the property name representation of the given name * * @param name The name to convert * @return The property name representation */ public static String getPropertyNameRepresentation(String name) { // Strip any package from the name. int pos = name.lastIndexOf('.'); if (pos != -1) { name = name.substring(pos + 1); } // Check whether the name begins with two upper case letters. if(name.length() > 1 && Character.isUpperCase(name.charAt(0)) && Character.isUpperCase(name.charAt(1))) { return name; } else { String propertyName = name.substring(0,1).toLowerCase(Locale.ENGLISH) + name.substring(1); if(propertyName.indexOf(' ') > -1) { propertyName = propertyName.replaceAll("\\s", ""); } return propertyName; } } /** * Returns the class name representation of the given name * * @param name The name to convert * @return The property name representation */ public static String getClassNameRepresentation(String name) { String className; StringBuffer buf = new StringBuffer(); if(name != null && name.length() > 0) { String[] tokens = name.split("[^\\w\\d]"); for (int i = 0; i < tokens.length; i++) { String token = tokens[i].trim(); buf.append(token.substring(0, 1).toUpperCase(Locale.ENGLISH)) .append(token.substring(1)); } } className = buf.toString(); return className; } /** * Shorter version of getPropertyNameRepresentation * @param name The name to convert * @return The property name version */ public static String getPropertyName(String name) { return getPropertyNameRepresentation(name); } /** * Shorter version of getPropertyNameRepresentation * @param clazz The clazz to convert * @return The property name version */ public static String getPropertyName(Class clazz) { return getPropertyNameRepresentation(clazz); } /** * Retrieves the script name representation of the supplied class. For example * MyFunkyGrailsScript would be my-funky-grails-script * * @param clazz The class to convert * @return The script name representation */ public static String getScriptName(Class clazz) { return getScriptName(clazz.getName()); } public static String getScriptName(String name) { if(name.endsWith(".groovy")) { name = name.substring(0, name.length()-7); } String naturalName = getNaturalName(getShortName(name)); return naturalName.replaceAll("\\s", "-").toLowerCase(); } /** * Calculates the class name from a script name in the form * my-funk-grails-script * * @param scriptName The script name * @return A class name */ public static String getNameFromScript(String scriptName) { return getClassNameForLowerCaseHyphenSeparatedName(scriptName); } /** * Converts foo-bar into fooBar * * @param name The lower case hyphen separated name * @return The property name equivalent */ public static String getPropertyNameForLowerCaseHyphenSeparatedName(String name) { return getPropertyName(getClassNameForLowerCaseHyphenSeparatedName(name)); } /** * Converts foo-bar into FooBar * * @param name The lower case hyphen separated name * @return The class name equivalent */ private static String getClassNameForLowerCaseHyphenSeparatedName(String name) { if(name.indexOf('-') > -1) { StringBuffer buf = new StringBuffer(); String[] tokens = name.split("-"); for (int i = 0; i < tokens.length; i++) { String token = tokens[i]; if(token == null || token.length() == 0) continue; buf.append(token.substring(0,1).toUpperCase()) .append(token.substring(1)); } return buf.toString(); } else { return name.substring(0,1).toUpperCase() + name.substring(1); } } /** * Converts a property name into its natural language equivalent eg ('firstName' becomes 'First Name') * @param name The property name to convert * @return The converted property name */ public static String getNaturalName(String name) { List words = new ArrayList(); int i = 0; char[] chars = name.toCharArray(); for (int j = 0; j < chars.length; j++) { char c = chars[j]; String w; if(i >= words.size()) { w = ""; words.add(i, w); } else { w = (String)words.get(i); } if(Character.isLowerCase(c) || Character.isDigit(c)) { if(Character.isLowerCase(c) && w.length() == 0) c = Character.toUpperCase(c); else if(w.length() > 1 && Character.isUpperCase(w.charAt(w.length() - 1)) ) { w = ""; words.add(++i,w); } words.set(i, w + c); } else if(Character.isUpperCase(c)) { if((i == 0 && w.length() == 0) || Character.isUpperCase(w.charAt(w.length() - 1)) ) { words.set(i, w + c); } else { words.add(++i, String.valueOf(c)); } } } StringBuffer buf = new StringBuffer(); for (Iterator j = words.iterator(); j.hasNext();) { String word = (String) j.next(); buf.append(word); if(j.hasNext()) buf.append(' '); } return buf.toString(); } /** * Convenience method for converting a collection to an Object[] * @param c The collection * @return An object array */ public static Object[] collectionToObjectArray(Collection c) { if(c == null) return new Object[0]; return c.toArray(new Object[c.size()]); } /** * Detect if left and right types are matching types. In particular, * test if one is a primitive type and the other is the corresponding * Java wrapper type. Primitive and wrapper classes may be passed to * either arguments. * * @param leftType * @param rightType * @return true if one of the classes is a native type and the other the object representation * of the same native type */ public static boolean isMatchBetweenPrimativeAndWrapperTypes(Class leftType, Class rightType) { if (leftType == null) { throw new NullPointerException("Left type is null!"); } else if (rightType == null) { throw new NullPointerException("Right type is null!"); } else { Class r = (Class)PRIMITIVE_TYPE_COMPATIBLE_CLASSES.get(leftType); return r == rightType; } } /** * <p>Tests whether or not the left hand type is compatible with the right hand type in Groovy * terms, i.e. can the left type be assigned a value of the right hand type in Groovy.</p> * <p>This handles Java primitive type equivalence and uses isAssignableFrom for all other types, * with a bit of magic for native types and polymorphism i.e. Number assigned an int. * If either parameter is null an exception is thrown</p> * * @param leftType The type of the left hand part of a notional assignment * @param rightType The type of the right hand part of a notional assignment * @return True if values of the right hand type can be assigned in Groovy to variables of the left hand type. */ public static boolean isGroovyAssignableFrom( Class leftType, Class rightType) { if (leftType == null) { throw new NullPointerException("Left type is null!"); } else if (rightType == null) { throw new NullPointerException("Right type is null!"); } else if (leftType == Object.class) { return true; } else if (leftType == rightType) { return true; } else { // check for primitive type equivalence Class r = (Class)PRIMITIVE_TYPE_COMPATIBLE_CLASSES.get(leftType); boolean result = r == rightType; if (!result) { // If no primitive <-> wrapper match, it may still be assignable // from polymorphic primitives i.e. Number -> int (AKA Integer) if (rightType.isPrimitive()) { // see if incompatible r = (Class)PRIMITIVE_TYPE_COMPATIBLE_CLASSES.get(rightType); if (r != null) { result = leftType.isAssignableFrom(r); } } else { // Otherwise it may just be assignable using normal Java polymorphism result = leftType.isAssignableFrom(rightType); } } return result; } } /** * <p>Work out if the specified property is readable and static. Java introspection does not * recognize this concept of static properties but Groovy does. We also consider public static fields * as static properties with no getters/setters</p> * * @param clazz The class to check for static property * @param propertyName The property name * @return true if the property with name propertyName has a static getter method */ public static boolean isStaticProperty( Class clazz, String propertyName) { Method getter = BeanUtils.findDeclaredMethod(clazz, getGetterName(propertyName), null); if (getter != null) { return isPublicStatic(getter); } else { try { Field f = clazz.getDeclaredField(propertyName); if (f != null) { return isPublicStatic(f); } } catch (NoSuchFieldException e) { } } return false; } /** * Determine whether the method is declared public static * @param m * @return True if the method is declared public static */ public static boolean isPublicStatic( Method m) { final int modifiers = m.getModifiers(); return Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers); } /** * Determine whether the field is declared public static * @param f * @return True if the field is declared public static */ public static boolean isPublicStatic( Field f) { final int modifiers = f.getModifiers(); return Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers); } /** * Calculate the name for a getter method to retrieve the specified property * @param propertyName * @return The name for the getter method for this property, if it were to exist, i.e. getConstraints */ public static String getGetterName(String propertyName) { return "get" + Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1); } /** * <p>Get a static property value, which has a public static getter or is just a public static field.</p> * * @param clazz The class to check for static property * @param name The property name * @return The value if there is one, or null if unset OR there is no such property */ public static Object getStaticPropertyValue(Class clazz, String name) { Method getter = BeanUtils.findDeclaredMethod(clazz, getGetterName(name), null); try { if (getter != null) { return getter.invoke(null, null); } else { Field f = clazz.getDeclaredField(name); if (f != null) { return f.get(null); } } } catch (Exception e) { } return null; } /** * <p>Looks for a property of the reference instance with a given name.</p> * <p>If found its value is returned. We follow the Java bean conventions with augmentation for groovy support * and static fields/properties. We will therefore match, in this order: * </p> * <ol> * <li>Standard public bean property (with getter or just public field, using normal introspection) * <li>Public static property with getter method * <li>Public static field * </ol> * * @return property value or null if no property found */ public static Object getPropertyOrStaticPropertyOrFieldValue(Object obj, String name) throws BeansException { BeanWrapper ref = new BeanWrapperImpl(obj); if (ref.isReadableProperty(name)) { return ref.getPropertyValue(name); } else { // Look for public fields if (isPublicField(obj, name)) { return getFieldValue(obj, name); } // Look for statics Class clazz = obj.getClass(); if (isStaticProperty(clazz, name)) { return getStaticPropertyValue(clazz, name); } else { return null; } } } /** * Get the value of a declared field on an object * * @param obj * @param name * @return The object value or null if there is no such field or access problems */ public static Object getFieldValue(Object obj, String name) { Class clazz = obj.getClass(); Field f = null; try { f = clazz.getDeclaredField(name); return f.get(obj); } catch (Exception e) { return null; } } /** * Work out if the specified object has a public field with the name supplied. * * @param obj * @param name * @return True if a public field with the name exists */ public static boolean isPublicField(Object obj, String name) { Class clazz = obj.getClass(); Field f = null; try { f = clazz.getDeclaredField(name); return Modifier.isPublic(f.getModifiers()); } catch (NoSuchFieldException e) { return false; } } /** * Checks whether the specified property is inherited from a super class * * @param clz The class to check * @param propertyName The property name * @return True if the property is inherited */ public static boolean isPropertyInherited(Class clz, String propertyName) { if(clz == null) return false; if(StringUtils.isBlank(propertyName)) throw new IllegalArgumentException("Argument [propertyName] cannot be null or blank"); Class superClass = clz.getSuperclass(); PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(superClass, propertyName); if (pd != null && pd.getReadMethod() != null) { return true; } return false; } /** * Creates a concrete collection for the suppied interface * @param interfaceType The interface * @return ArrayList for List, TreeSet for SortedSet, HashSet for Set etc. */ public static Collection createConcreteCollection(Class interfaceType) { Collection elements; if(interfaceType.equals(List.class)) { elements = new ArrayList(); } else if(interfaceType.equals(SortedSet.class)) { elements = new TreeSet(); } else { elements = new HashSet(); } return elements; } /** * Retrieves the logical class name of a Grails artifact given the Grails class * and a specified trailing name * * @param clazz The class * @param trailingName The trailing name such as "Controller" or "TagLib" * @return The logical class name */ public static String getLogicalName(Class clazz, String trailingName) { return getLogicalName(clazz.getName(), trailingName); } /** * Retrieves the logical name of the classs without the trailing name * @param name The name of the class * @param trailingName The trailing name * @return The logical name */ public static String getLogicalName(String name, String trailingName ) { if(!StringUtils.isBlank(trailingName)) { String shortName = getShortName(name); if(shortName.indexOf( trailingName ) > - 1) { return shortName.substring(0, shortName.length() - trailingName.length()); } } return name; } public static String getLogicalPropertyName(String className, String trailingName) { return getLogicalName(getPropertyName(className), trailingName); } /** * Retrieves the name of a setter for the specified property name * @param propertyName The property name * @return The setter equivalent */ public static String getSetterName(String propertyName) { return PROPERTY_SET_PREFIX+propertyName.substring(0,1).toUpperCase()+ propertyName.substring(1); } /** * Returns true if the name of the method specified and the number of arguments make it a javabean property * * @param name True if its a Javabean property * @param args The arguments * @return True if it is a javabean property method */ public static boolean isGetter(String name, Class[] args) { if(StringUtils.isBlank(name) || args == null)return false; if(args.length != 0)return false; if(name.startsWith("get")) { name = name.substring(3); if(name.length() > 0 && Character.isUpperCase(name.charAt(0))) return true; } else if(name.startsWith("is")) { name = name.substring(2); if(name.length() > 0 && Character.isUpperCase(name.charAt(0))) return true; } return false; } /** * Returns a property name equivalent for the given getter name or null if it is not a getter * * @param getterName The getter name * @return The property name equivalent */ public static String getPropertyForGetter(String getterName) { if(StringUtils.isBlank(getterName))return null; if(getterName.startsWith("get")) { String prop = getterName.substring(3); return convertPropertyName(prop); } else if(getterName.startsWith("is")) { String prop = getterName.substring(2); return convertPropertyName(prop); } return null; } private static String convertPropertyName(String prop) { if(Character.isUpperCase(prop.charAt(0)) && Character.isUpperCase(prop.charAt(1))) { return prop; } else if(Character.isDigit(prop.charAt(0))) { return prop; } else { return Character.toLowerCase(prop.charAt(0)) + prop.substring(1); } } /** * Returns a property name equivalent for the given setter name or null if it is not a getter * * @param setterName The setter name * @return The property name equivalent */ public static String getPropertyForSetter(String setterName) { if(StringUtils.isBlank(setterName))return null; if(setterName.startsWith("set")) { String prop = setterName.substring(3); return convertPropertyName(prop); } return null; } public static boolean isSetter(String name, Class[] args) { if(StringUtils.isBlank(name) || args == null)return false; if(name.startsWith("set")) { if(args.length != 1) return false; name = name.substring(3); if(name.length() > 0 && Character.isUpperCase(name.charAt(0))) return true; } return false; } public static MetaClass getExpandoMetaClass(Class clazz) { MetaClassRegistry registry = GroovySystem.getMetaClassRegistry(); Assert.isTrue(registry.getMetaClassCreationHandler() instanceof ExpandoMetaClassCreationHandle, "Grails requires an instance of [ExpandoMetaClassCreationHandle] to be set in Groovy's MetaClassRegistry!"); MetaClass mc = registry.getMetaClass(clazz); AdaptingMetaClass adapter = null; if(mc instanceof AdaptingMetaClass) { adapter = (AdaptingMetaClass) mc; mc= ((AdaptingMetaClass)mc).getAdaptee(); } if(!(mc instanceof ExpandoMetaClass)) { // removes cached version registry.removeMetaClass(clazz); mc= registry.getMetaClass(clazz); if(adapter != null) { adapter.setAdaptee(mc); } } Assert.isTrue(mc instanceof ExpandoMetaClass,"BUG! Method must return an instance of [ExpandoMetaClass]!"); return mc; } /** * Returns true if the specified clazz parameter is either the same as, or is a superclass or superinterface * of, the specified type parameter. Converts primitive types to compatible class automatically. * * @param clazz * @param type * @return True if the class is a taglib * @see java.lang.Class#isAssignableFrom(Class) */ public static boolean isAssignableOrConvertibleFrom(Class clazz, Class type) { if (type == null || clazz == null) { return false; } else if (type.isPrimitive()) { // convert primitive type to compatible class Class primitiveClass = (Class)GrailsClassUtils.PRIMITIVE_TYPE_COMPATIBLE_CLASSES.get(type); if (primitiveClass == null) { // no compatible class found for primitive type return false; } else { return clazz.isAssignableFrom(primitiveClass); } } else { return clazz.isAssignableFrom(type); } } /** * Retrieves a boolean value from a Map for the given key * * @param key The key that references the boolean value * @param map The map to look in * @return A boolean value which will be false if the map is null, the map doesn't contain the key or the value is false */ public static boolean getBooleanFromMap(String key, Map map) { if(map == null) return false; if(map.containsKey(key)) { Object o = map.get(key); if(o == null)return false; else if(o instanceof Boolean) { return ((Boolean)o).booleanValue(); } else { return Boolean.valueOf(o.toString()).booleanValue(); } } return false; } /** * Returns the class name for the given logical name and trailing name. For example "person" and "Controller" would evaluate to "PersonController" * * @param logicalName The logical name * @param trailingName The trailing name * @return The class name */ public static String getClassName(String logicalName, String trailingName) { if(StringUtils.isBlank(logicalName)) throw new IllegalArgumentException("Argument [logicalName] cannot be null or blank"); String className = logicalName.substring(0,1).toUpperCase() + logicalName.substring(1); if(trailingName != null) className = className + trailingName; return className; } /** * Checks whether the given class is a JDK 1.5 enum or not * * @param type The class to check * @return True if it is an enum */ public static boolean isJdk5Enum(Class type) { if (JdkVersion.getMajorJavaVersion() >= JdkVersion.JAVA_15) { Method m = BeanUtils.findMethod(type.getClass(),"isEnum", null); if(m == null) return false; try { Object result = m.invoke(type, null); return result instanceof Boolean && ((Boolean) result).booleanValue(); } catch (Exception e ) { return false; } } else { return false; } } }

The table below shows all metrics for GrailsClassUtils.java.

MetricValueDescription
BLOCKS155.00Number of blocks
BLOCK_COMMENT14.00Number of block comment lines
COMMENTS343.00Comment lines
COMMENT_DENSITY 0.83Comment density
COMPARISONS138.00Number of comparison operators
CYCLOMATIC181.00Cyclomatic complexity
DECL_COMMENTS46.00Comments in declarations
DOC_COMMENT312.00Number of javadoc comment lines
ELOC413.00Effective lines of code
EXEC_COMMENTS16.00Comments in executable code
EXITS108.00Procedure exits
FUNCTIONS50.00Number of function declarations
HALSTEAD_DIFFICULTY87.84Halstead difficulty
HALSTEAD_EFFORT 0.00Halstead effort
INTERFACE_COMPLEXITY200.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 2.00JAVA0008 Empty catch block
JAVA0009 0.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 1.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 0.00JAVA0029 Private method not used
JAVA0030 0.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
JAVA003428.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 0.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 0.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 0.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 1.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 2.00JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
JAVA0109 0.00JAVA0109 Incorrect javadoc: no parameter 'parameter'
JAVA0110 0.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 0.00JAVA0113 Incorrect javadoc: no @author tag
JAVA0114 1.00JAVA0114 Incorrect javadoc: no @version tag
JAVA0115 1.00JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
JAVA0116 1.00JAVA0116 Missing javadoc: field 'field'
JAVA0117 4.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 0.00JAVA0125 Continue statement with label
JAVA0126 1.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 1.00JAVA0136 N methods defined in class (maximum: M)
JAVA0137 0.00JAVA0137 Non-abstract class missing constructor
JAVA0138 0.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 2.00JAVA0144 Line exceeds maximum M characters
JAVA0145243.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 8.00JAVA0166 Generic exception caught
JAVA0167 0.00JAVA0167 ThreadDeath not rethrown
JAVA0169 0.00JAVA0169 Unnecessary catch block: exception 'exception'
JAVA0170 0.00JAVA0170 Caught exception not derived from java.lang.Exception
JAVA0171 0.00JAVA0171 Unused local variable
JAVA0173 1.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 3.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 6.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 2.00JAVA0286 Dereference of null variable
JAVA0287 0.00JAVA0287 Unnecessary null check
JAVA0288 0.00JAVA0288 Inconsistent null check
LINES1029.00Number of lines in the source file
LINE_COMMENT17.00Number of line comments
LOC587.00Lines of code
LOGICAL_LINES257.00Number of statements
LOOPS 7.00Number of loops
NEST_DEPTH 5.00Maximum nesting depth
OPERANDS1321.00Number of operands
OPERATORS2667.00Number of operators
PARAMS79.00Number of formal parameter declarations
PROGRAM_LENGTH3988.00Halstead program length
PROGRAM_VOCAB443.00Halstead program vocabulary
PROGRAM_VOLUME 0.00Halstead program volume
RETURNS121.00Number of return points from functions
SIZE35296.00Size of the file in bytes
UNIQUE_OPERANDS391.00Number of unique operands
UNIQUE_OPERATORS52.00Number of unique operators
WHITESPACE99.00Number of whitespace lines