You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by em...@apache.org on 2021/04/25 16:46:32 UTC

[groovy] branch master updated: reduce occurrences of "new Class[0]"

This is an automated email from the ASF dual-hosted git repository.

emilles pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git


The following commit(s) were added to refs/heads/master by this push:
     new 7f82766  reduce occurrences of "new Class[0]"
7f82766 is described below

commit 7f82766a95c94ae7bd9c5f4e800d2187ce3c40b4
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Sun Apr 25 11:10:28 2021 -0500

    reduce occurrences of "new Class[0]"
---
 .../tailrec/VariableExpressionReplacer.groovy      | 27 ++++++++--------------
 src/main/java/groovy/lang/ExpandoMetaClass.java    | 27 +++++++++++-----------
 src/main/java/groovy/util/ProxyGenerator.java      |  8 +++----
 .../codehaus/groovy/reflection/ParameterTypes.java |  5 +---
 .../runtime/metaclass/ClosureMetaMethod.java       |  8 +++----
 .../org/codehaus/groovy/vmplugin/v8/Java8.java     |  4 ++--
 src/test-resources/core/Groovydoc_01x.groovy       |  2 +-
 .../codehaus/groovy/reflection/SecurityTest.java   |  4 ++--
 .../groovy/groovy/swing/StrangeBeanBeanInfo.java   | 10 ++++----
 9 files changed, 42 insertions(+), 53 deletions(-)

diff --git a/src/main/groovy/org/codehaus/groovy/transform/tailrec/VariableExpressionReplacer.groovy b/src/main/groovy/org/codehaus/groovy/transform/tailrec/VariableExpressionReplacer.groovy
index b56f0bd..9dbb801 100644
--- a/src/main/groovy/org/codehaus/groovy/transform/tailrec/VariableExpressionReplacer.groovy
+++ b/src/main/groovy/org/codehaus/groovy/transform/tailrec/VariableExpressionReplacer.groovy
@@ -18,6 +18,7 @@
  */
 package org.codehaus.groovy.transform.tailrec
 
+import groovy.transform.AutoFinal
 import groovy.transform.CompileStatic
 import org.codehaus.groovy.ast.ASTNode
 import org.codehaus.groovy.ast.CodeVisitorSupport
@@ -37,6 +38,7 @@ import org.codehaus.groovy.ast.stmt.SwitchStatement
 import org.codehaus.groovy.ast.stmt.SynchronizedStatement
 import org.codehaus.groovy.ast.stmt.ThrowStatement
 import org.codehaus.groovy.ast.stmt.WhileStatement
+import org.codehaus.groovy.ast.tools.GeneralUtils
 
 import java.lang.reflect.Method
 
@@ -49,7 +51,7 @@ import java.lang.reflect.Method
  * - to swap the access of method args with the access to iteration variables
  * - to swap the access of iteration variables with the access of temp vars
  */
-@CompileStatic
+@AutoFinal @CompileStatic
 class VariableExpressionReplacer extends CodeVisitorSupport {
 
     Closure<Boolean> when = { VariableExpression node -> false }
@@ -129,7 +131,6 @@ class VariableExpressionReplacer extends CodeVisitorSupport {
         super.visitSynchronizedStatement(statement)
     }
 
-    @SuppressWarnings('Instanceof')
     private void replaceExpressionPropertyWhenNecessary(ASTNode node, String propName = 'expression', Class propClass = Expression) {
         Expression expr = getExpression(node, propName)
 
@@ -146,25 +147,17 @@ class VariableExpressionReplacer extends CodeVisitorSupport {
 
     private void replaceExpression(ASTNode node, String propName, Class propClass, Expression oldExpr, Expression newExpr) {
         //Use reflection to enable CompileStatic
-        String setterName = 'set' + capitalizeFirst(propName)
-        Method setExpressionMethod = node.class.getMethod(setterName, [propClass].toArray(new Class[1]))
-        newExpr.sourcePosition = oldExpr
+        String setterName = GeneralUtils.getSetterName(propName)
+        Method setExpressionMethod = node.class.getMethod(setterName, propClass)
         newExpr.copyNodeMetaData(oldExpr)
-        setExpressionMethod.invoke(node, [newExpr].toArray())
+        newExpr.setSourcePosition(oldExpr)
+        setExpressionMethod.invoke(node, newExpr)
     }
 
     private Expression getExpression(ASTNode node, String propName) {
         //Use reflection to enable CompileStatic
-        String getterName = 'get' + capitalizeFirst(propName)
-        Method getExpressionMethod = node.class.getMethod(getterName, new Class[0])
-        getExpressionMethod.invoke(node, new Object[0]) as Expression
+        String getterName = GeneralUtils.getGetterName(propName)
+        Method getExpressionMethod = node.class.getMethod(getterName)
+        getExpressionMethod.invoke(node) as Expression
     }
-
-    private String capitalizeFirst(String propName) {
-        propName[0].toUpperCase() + propName[1..-1]
-    }
-
-
 }
-
-
diff --git a/src/main/java/groovy/lang/ExpandoMetaClass.java b/src/main/java/groovy/lang/ExpandoMetaClass.java
index 221bd53..d1343ec 100644
--- a/src/main/java/groovy/lang/ExpandoMetaClass.java
+++ b/src/main/java/groovy/lang/ExpandoMetaClass.java
@@ -57,6 +57,8 @@ import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.ReentrantReadWriteLock;
 
+import static org.codehaus.groovy.runtime.MetaClassHelper.EMPTY_TYPE_ARRAY;
+
 /**
  * ExpandoMetaClass is a MetaClass that behaves like an Expando, allowing the addition or replacement
  * of methods, properties and constructors on the fly.
@@ -199,7 +201,7 @@ import java.util.concurrent.locks.ReentrantReadWriteLock;
  * ndq.metaClass {
  *     mixin ArrayDeque
  *     mixin HashSet
- *     leftShift = { Object o  {@code ->} 
+ *     leftShift = { Object o  {@code ->}
  *         if (!mixedIn[Set].contains(o)) {
  *             mixedIn[Queue].push(o)
  *             mixedIn[Set].add(o)
@@ -256,7 +258,6 @@ import java.util.concurrent.locks.ReentrantReadWriteLock;
  */
 public class ExpandoMetaClass extends MetaClassImpl implements GroovyObject {
 
-    private static final Class[] EMPTY_CLASS_ARRAY = new Class[0];
     private static final String META_CLASS = "metaClass";
     private static final String CLASS = "class";
     private static final String META_METHODS = "metaMethods";
@@ -279,10 +280,10 @@ public class ExpandoMetaClass extends MetaClassImpl implements GroovyObject {
     private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
     private final Lock readLock = rwl.readLock();
     private final Lock writeLock = rwl.writeLock();
-    
+
     private final boolean allowChangesAfterInit;
     public boolean inRegistry;
-    
+
     private final Set<MetaMethod> inheritedMetaMethods = new HashSet<MetaMethod>();
     private final Map<String, MetaProperty> beanPropertyCache = new ConcurrentHashMap<String, MetaProperty>(16, 0.75f, 1);
     private final Map<String, MetaProperty> staticBeanPropertyCache = new ConcurrentHashMap<String, MetaProperty>(16, 0.75f, 1);
@@ -300,14 +301,14 @@ public class ExpandoMetaClass extends MetaClassImpl implements GroovyObject {
     public ExpandoMetaClass(Class theClass, boolean register, boolean allowChangesAfterInit, MetaMethod[] add) {
         this(GroovySystem.getMetaClassRegistry(), theClass, register, allowChangesAfterInit, add);
     }
-    
+
     public ExpandoMetaClass(MetaClassRegistry registry, Class theClass, boolean register, boolean allowChangesAfterInit, MetaMethod[] add) {
         super(registry, theClass, add);
         this.myMetaClass = InvokerHelper.getMetaClass(getClass());
         this.inRegistry = register;
         this.allowChangesAfterInit = allowChangesAfterInit;
     }
-    
+
     /**
      * Constructs a new ExpandoMetaClass instance for the given class
      *
@@ -370,11 +371,11 @@ public class ExpandoMetaClass extends MetaClassImpl implements GroovyObject {
                 MetaMethod method = new MixinInstanceMetaMethod(metaMethod, mixin);
 
                 if (method.getParameterTypes().length == 1 && !method.getParameterTypes()[0].isPrimitive) {
-                    MetaMethod noParam = pickMethod(methodName, EMPTY_CLASS_ARRAY);
-                    // if the current call itself is with empty arg class array, no need to recurse with 'new Class[0]'
+                    MetaMethod noParam = pickMethod(methodName, EMPTY_TYPE_ARRAY);
+                    // if the current call itself is with empty arg class array, no need to recurse
                     if (noParam == null && arguments.length != 0) {
                         try {
-                            findMixinMethod(methodName, EMPTY_CLASS_ARRAY);
+                            findMixinMethod(methodName, EMPTY_TYPE_ARRAY);
                         } catch (MethodSelectionException msex) {
                             /*
                              * Here we just additionally tried to find another no-arg mixin method of the same name and register that as well, if found.
@@ -468,7 +469,7 @@ public class ExpandoMetaClass extends MetaClassImpl implements GroovyObject {
 
     /**
      * Call to enable global use of ExpandoMetaClass within the registry.
-     * This has the advantage that inheritance will function correctly and 
+     * This has the advantage that inheritance will function correctly and
      * metaclass modifications will also apply to existing objects,
      * but has a higher memory usage on the JVM than normal Groovy
      */
@@ -762,7 +763,7 @@ public class ExpandoMetaClass extends MetaClassImpl implements GroovyObject {
         if (metaMethod != null) {
             // we have to use doMethodInvoke here instead of simply invoke,
             // because getMetaMethod may provide a method that can not be called
-            // without further argument transformation, which is done only in 
+            // without further argument transformation, which is done only in
             // doMethodInvoke
             return metaMethod.doMethodInvoke(this, argsArr);
         }
@@ -846,7 +847,7 @@ public class ExpandoMetaClass extends MetaClassImpl implements GroovyObject {
             readLock.unlock();
         }
     }
-    
+
     @Override
     protected void checkInitalised() {
         try {
@@ -1348,7 +1349,7 @@ public class ExpandoMetaClass extends MetaClassImpl implements GroovyObject {
             return new PogoMetaClassSite(site, this);
         return super.createPogoCallCurrentSite(site, sender, args);
     }
-    
+
     @Override
     public MetaMethod retrieveConstructor(Object[] args) {
         Class[] params = MetaClassHelper.convertToTypeArray(args);
diff --git a/src/main/java/groovy/util/ProxyGenerator.java b/src/main/java/groovy/util/ProxyGenerator.java
index 06d6a2a..0e92ae0 100644
--- a/src/main/java/groovy/util/ProxyGenerator.java
+++ b/src/main/java/groovy/util/ProxyGenerator.java
@@ -24,6 +24,7 @@ import groovy.lang.GroovyObject;
 import groovy.lang.GroovySystem;
 import groovy.lang.MetaClass;
 import org.codehaus.groovy.runtime.InvokerHelper;
+import org.codehaus.groovy.runtime.MetaClassHelper;
 import org.codehaus.groovy.runtime.ProxyGeneratorAdapter;
 import org.codehaus.groovy.runtime.memoize.LRUCache;
 import org.codehaus.groovy.runtime.typehandling.GroovyCastException;
@@ -47,8 +48,7 @@ import java.util.Set;
  * maps of closures and/or extend classes/delegates.
  */
 public class ProxyGenerator {
-    private static final Class[] EMPTY_CLASS_ARRAY = new Class[0];
-    private static final Class[] EMPTY_INTERFACE_ARRAY = EMPTY_CLASS_ARRAY;
+    private static final Class[] EMPTY_INTERFACE_ARRAY = MetaClassHelper.EMPTY_TYPE_ARRAY;
     private static final Map<Object,Object> EMPTY_CLOSURE_MAP = Collections.emptyMap();
     private static final Set<String> EMPTY_KEYSET = Collections.emptySet();
 
@@ -210,7 +210,7 @@ public class ProxyGenerator {
     private ProxyGeneratorAdapter createAdapter(Map closureMap, List<Class> interfaces, Class delegateClass, Class baseClass) {
         // According to https://shipilev.net/blog/2016/arrays-wisdom-ancients/#_conclusion
         // toArray(new T[0]) seems faster, safer, and contractually cleaner, and therefore should be the default choice now.
-        Class[] intfs = interfaces != null ? interfaces.toArray(EMPTY_CLASS_ARRAY) : EMPTY_INTERFACE_ARRAY;
+        Class[] intfs = interfaces != null ? interfaces.toArray(EMPTY_INTERFACE_ARRAY) : EMPTY_INTERFACE_ARRAY;
         Class base = baseClass;
         if (base == null) {
             if (intfs.length > 0) {
@@ -245,7 +245,7 @@ public class ProxyGenerator {
         };
         GroovySystem.getMetaClassRegistry().setMetaClass(ProxyGenerator.class, newMetaClass);
     }
-    
+
     private static final class CacheKey {
         private static final Comparator<Class> INTERFACE_COMPARATOR = (o1, o2) -> {
             // Traits order *must* be preserved
diff --git a/src/main/java/org/codehaus/groovy/reflection/ParameterTypes.java b/src/main/java/org/codehaus/groovy/reflection/ParameterTypes.java
index 4b7cc45..86056e5 100644
--- a/src/main/java/org/codehaus/groovy/reflection/ParameterTypes.java
+++ b/src/main/java/org/codehaus/groovy/reflection/ParameterTypes.java
@@ -26,8 +26,6 @@ import org.codehaus.groovy.runtime.wrappers.Wrapper;
 import java.lang.reflect.Array;
 
 public class ParameterTypes {
-    private static final Class[] NO_PARAMETERS = new Class[0];
-
     protected volatile Class[] nativeParamTypes;
     protected volatile CachedClass[] parameterTypes;
 
@@ -76,10 +74,9 @@ public class ParameterTypes {
 
         Class[] npt = nativeParamTypes == null ? getPT() : nativeParamTypes;
         if (npt.length == 0) {
-            nativeParamTypes = NO_PARAMETERS;
+            nativeParamTypes = MetaClassHelper.EMPTY_TYPE_ARRAY;
             setParametersTypes(CachedClass.EMPTY_ARRAY);
         } else {
-
             CachedClass[] pt = new CachedClass[npt.length];
             for (int i = 0; i != npt.length; ++i)
                 pt[i] = ReflectionCache.getCachedClass(npt[i]);
diff --git a/src/main/java/org/codehaus/groovy/runtime/metaclass/ClosureMetaMethod.java b/src/main/java/org/codehaus/groovy/runtime/metaclass/ClosureMetaMethod.java
index 39eb6f8..0e1bcca 100644
--- a/src/main/java/org/codehaus/groovy/runtime/metaclass/ClosureMetaMethod.java
+++ b/src/main/java/org/codehaus/groovy/runtime/metaclass/ClosureMetaMethod.java
@@ -26,6 +26,7 @@ import org.codehaus.groovy.reflection.CachedMethod;
 import org.codehaus.groovy.reflection.ReflectionCache;
 import org.codehaus.groovy.runtime.GeneratedClosure;
 import org.codehaus.groovy.runtime.InvokerHelper;
+import org.codehaus.groovy.runtime.MetaClassHelper;
 import org.codehaus.groovy.runtime.MethodClosure;
 
 import java.lang.reflect.Modifier;
@@ -40,7 +41,6 @@ import java.util.List;
  */
 public class ClosureMetaMethod extends MetaMethod implements ClosureInvokingMethod {
 
-    private static final Class[] EMPTY_CLASS_ARRAY = new Class[0];
     private final Closure callable;
     private final CachedMethod doCall;
     private final String name;
@@ -106,7 +106,7 @@ public class ClosureMetaMethod extends MetaMethod implements ClosureInvokingMeth
             Class ownerClass = (Class) (owner instanceof Class ? owner : owner.getClass());
             for (CachedMethod method : ReflectionCache.getCachedClass(ownerClass).getMethods() ) {
                 if (method.getName().equals(methodClosure.getMethod())) {
-                    MetaMethod metaMethod = new MethodClosureMetaMethod(name, declaringClass, closure, method); 
+                    MetaMethod metaMethod = new MethodClosureMetaMethod(name, declaringClass, closure, method);
                     res.add(adjustParamTypesForStdMethods(metaMethod, name));
                 }
             }
@@ -127,10 +127,10 @@ public class ClosureMetaMethod extends MetaMethod implements ClosureInvokingMeth
         }
         return res;
     }
-    
+
     private static MetaMethod adjustParamTypesForStdMethods(MetaMethod metaMethod, String methodName) {
         Class[] nativeParamTypes = metaMethod.getNativeParameterTypes();
-        nativeParamTypes = (nativeParamTypes != null) ? nativeParamTypes : EMPTY_CLASS_ARRAY;
+        nativeParamTypes = (nativeParamTypes != null) ? nativeParamTypes : MetaClassHelper.EMPTY_TYPE_ARRAY;
         // for methodMissing, first parameter should be String type - to allow overriding of this method without
         // type String explicitly specified for first parameter (missing method name) - GROOVY-2951
         if("methodMissing".equals(methodName) && nativeParamTypes.length == 2 && nativeParamTypes[0] != String.class) {
diff --git a/src/main/java/org/codehaus/groovy/vmplugin/v8/Java8.java b/src/main/java/org/codehaus/groovy/vmplugin/v8/Java8.java
index e16bba9..3f54df0 100644
--- a/src/main/java/org/codehaus/groovy/vmplugin/v8/Java8.java
+++ b/src/main/java/org/codehaus/groovy/vmplugin/v8/Java8.java
@@ -40,6 +40,7 @@ import org.codehaus.groovy.ast.expr.ListExpression;
 import org.codehaus.groovy.ast.expr.PropertyExpression;
 import org.codehaus.groovy.ast.stmt.ReturnStatement;
 import org.codehaus.groovy.reflection.ReflectionUtils;
+import org.codehaus.groovy.runtime.MetaClassHelper;
 import org.codehaus.groovy.vmplugin.VMPlugin;
 import org.codehaus.groovy.vmplugin.VMPluginFactory;
 
@@ -76,7 +77,6 @@ import java.util.List;
 public class Java8 implements VMPlugin {
 
     private static final Class<?>[] PLUGIN_DGM = {PluginDefaultGroovyMethods.class};
-    private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class[0];
     private static final Method[] EMPTY_METHOD_ARRAY = new Method[0];
     private static final Annotation[] EMPTY_ANNOTATION_ARRAY = new Annotation[0];
     private static final Permission ACCESS_PERMISSION = new ReflectPermission("suppressAccessChecks");
@@ -304,7 +304,7 @@ public class Java8 implements VMPlugin {
 
     @Override
     public Class<?>[] getPluginStaticGroovyMethods() {
-        return EMPTY_CLASS_ARRAY;
+        return MetaClassHelper.EMPTY_TYPE_ARRAY;
     }
 
     private void setAnnotationMetaData(Annotation[] annotations, AnnotatedNode an) {
diff --git a/src/test-resources/core/Groovydoc_01x.groovy b/src/test-resources/core/Groovydoc_01x.groovy
index 4aaa473..51b7ba2 100644
--- a/src/test-resources/core/Groovydoc_01x.groovy
+++ b/src/test-resources/core/Groovydoc_01x.groovy
@@ -57,7 +57,7 @@ class AA {
 }
 
 assert AA.class.groovydoc.content.contains('class AA')
-assert AA.class.getMethod('m', new Class[0]).groovydoc.content.contains('method m')
+assert AA.class.getMethod('m').groovydoc.content.contains('method m')
 assert AA.class.getConstructor().groovydoc.content.contains('constructor AA')
 assert AA.class.getField('SOME_FIELD').groovydoc.content.contains('field SOME_FIELD')
 assert AA.class.getDeclaredClasses().find {it.simpleName.contains('InnerClass')}.groovydoc.content.contains('class InnerClass')
diff --git a/src/test/org/codehaus/groovy/reflection/SecurityTest.java b/src/test/org/codehaus/groovy/reflection/SecurityTest.java
index 41f7b03..d466847 100644
--- a/src/test/org/codehaus/groovy/reflection/SecurityTest.java
+++ b/src/test/org/codehaus/groovy/reflection/SecurityTest.java
@@ -21,10 +21,10 @@ package org.codehaus.groovy.reflection;
 import groovy.lang.GroovyObjectSupport;
 import groovy.test.GroovyTestCase;
 import org.codehaus.groovy.runtime.InvokerInvocationException;
+
 import java.lang.reflect.Field;
 import java.lang.reflect.Method;
 import java.lang.reflect.ReflectPermission;
-import java.math.BigDecimal;
 import java.nio.ByteBuffer;
 import java.security.AccessControlException;
 import java.security.Permission;
@@ -221,7 +221,7 @@ public class SecurityTest extends GroovyTestCase {
         if (isAtLeastJdk("9.0")) {
             return;
         }
-        cachedMethodUnderTest = createCachedMethod(ClassLoader.class, "getBootstrapClassPath", new Class[0]);
+        cachedMethodUnderTest = createCachedMethod(ClassLoader.class, "getBootstrapClassPath");
         System.setSecurityManager(restrictiveSecurityManager);
 
         try {
diff --git a/subprojects/groovy-swing/src/test/groovy/groovy/swing/StrangeBeanBeanInfo.java b/subprojects/groovy-swing/src/test/groovy/groovy/swing/StrangeBeanBeanInfo.java
index 8e2f97b..c7cd689 100644
--- a/subprojects/groovy-swing/src/test/groovy/groovy/swing/StrangeBeanBeanInfo.java
+++ b/subprojects/groovy-swing/src/test/groovy/groovy/swing/StrangeBeanBeanInfo.java
@@ -23,19 +23,17 @@ import java.beans.SimpleBeanInfo;
 import java.lang.reflect.Method;
 
 public class StrangeBeanBeanInfo extends SimpleBeanInfo {
-    private static final Class[] EMPTY_CLASS_ARRAY = new Class[0];
-
     public EventSetDescriptor[] getEventSetDescriptors() {
         try {
             Method[] events = StrangeEventListener.class.getMethods();
             Method addListener = StrangeBean.class.getMethod("addStrangeEventListener", StrangeEventListener.class);
             Method removeListener = StrangeBean.class.getMethod("removeStrangeEventListener", StrangeEventListener.class);
-            Method getListeners = StrangeBean.class.getMethod("getStrangeEventListeners", EMPTY_CLASS_ARRAY);
-            
+            Method getListeners = StrangeBean.class.getMethod("getStrangeEventListeners");
+
             return new EventSetDescriptor[] {
-                new EventSetDescriptor( 
+                new EventSetDescriptor(
                         "strangeEvent",
-                        StrangeEventListener.class, 
+                        StrangeEventListener.class,
                         events,
                         addListener,
                         removeListener,