Use Method.getParameterCount() where possible
Christoph Dreis
christoph.dreis at freenet.de
Fri Apr 3 10:19:25 UTC 2020
Hi,
I noticed that the JDK itself still uses Method.getParameterTypes().length in a couple of places.
This could be replaced with Method.getParameterCount() to avoid unnecessary cloning overhead.
While this is often optimized away, I guess it's still good to not rely on that. Additionally, it's a little more concise to read.
If you think this is worthwhile, I would need someone to sponsor that tiny change.
P.S.: There is another occurrence in ForkJoinTask where I wasn't sure if I should change that, because it's usually changed under the JSR166 umbrella afaik.
Cheers,
Christoph
==== PATCH ====
diff --git a/src/java.base/share/classes/java/lang/invoke/MethodHandleProxies.java b/src/java.base/share/classes/java/lang/invoke/MethodHandleProxies.java
--- a/src/java.base/share/classes/java/lang/invoke/MethodHandleProxies.java
+++ b/src/java.base/share/classes/java/lang/invoke/MethodHandleProxies.java
@@ -276,13 +276,13 @@
switch (m.getName()) {
case "toString":
return (m.getReturnType() == String.class
- && m.getParameterTypes().length == 0);
+ && m.getParameterCount() == 0);
case "hashCode":
return (m.getReturnType() == int.class
- && m.getParameterTypes().length == 0);
+ && m.getParameterCount() == 0);
case "equals":
return (m.getReturnType() == boolean.class
- && m.getParameterTypes().length == 1
+ && m.getParameterCount() == 1
&& m.getParameterTypes()[0] == Object.class);
}
return false;
diff --git a/src/java.base/share/classes/java/lang/reflect/Executable.java b/src/java.base/share/classes/java/lang/reflect/Executable.java
--- a/src/java.base/share/classes/java/lang/reflect/Executable.java
+++ b/src/java.base/share/classes/java/lang/reflect/Executable.java
@@ -378,7 +378,7 @@
private void verifyParameters(final Parameter[] parameters) {
final int mask = Modifier.FINAL | Modifier.SYNTHETIC | Modifier.MANDATED;
- if (getParameterTypes().length != parameters.length)
+ if (getParameterCount() != parameters.length)
throw new MalformedParametersException("Wrong number of parameters in MethodParameters attribute");
for (Parameter parameter : parameters) {
diff --git a/src/java.base/share/classes/sun/reflect/annotation/AnnotationType.java b/src/java.base/share/classes/sun/reflect/annotation/AnnotationType.java
--- a/src/java.base/share/classes/sun/reflect/annotation/AnnotationType.java
+++ b/src/java.base/share/classes/sun/reflect/annotation/AnnotationType.java
@@ -121,7 +121,7 @@
if (Modifier.isPublic(method.getModifiers()) &&
Modifier.isAbstract(method.getModifiers()) &&
!method.isSynthetic()) {
- if (method.getParameterTypes().length != 0) {
+ if (method.getParameterCount() != 0) {
throw new IllegalArgumentException(method + " has params");
}
String name = method.getName();
More information about the core-libs-dev
mailing list