我可以使用Java反射获取方法参数名称吗?
2022-08-31 07:57:54
如果我有这样的课程:
public class Whatever
{
public void aMethod(int aParam);
}
有没有办法知道使用名为 的参数,即类型?aMethod
aParam
int
如果我有这样的课程:
public class Whatever
{
public void aMethod(int aParam);
}
有没有办法知道使用名为 的参数,即类型?aMethod
aParam
int
在 Java 8 中,您可以执行以下操作:
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;
public final class Methods {
public static List<String> getParameterNames(Method method) {
Parameter[] parameters = method.getParameters();
List<String> parameterNames = new ArrayList<>();
for (Parameter parameter : parameters) {
if(!parameter.isNamePresent()) {
throw new IllegalArgumentException("Parameter names are not present!");
}
String parameterName = parameter.getName();
parameterNames.add(parameterName);
}
return parameterNames;
}
private Methods(){}
}
因此,对于您的班级,我们可以进行手动测试:Whatever
import java.lang.reflect.Method;
public class ManualTest {
public static void main(String[] args) {
Method[] declaredMethods = Whatever.class.getDeclaredMethods();
for (Method declaredMethod : declaredMethods) {
if (declaredMethod.getName().equals("aMethod")) {
System.out.println(Methods.getParameterNames(declaredMethod));
break;
}
}
}
}
如果您已将参数传递给 Java 8 编译器,则应打印该参数。[aParam]
-parameters
对于 Maven 用户:
<properties>
<!-- PLUGIN VERSIONS -->
<maven-compiler-plugin.version>3.1</maven-compiler-plugin.version>
<!-- OTHER PROPERTIES -->
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<!-- Original answer -->
<compilerArgument>-parameters</compilerArgument>
<!-- Or, if you use the plugin version >= 3.6.2 -->
<parameters>true</parameters>
<testCompilerArgument>-parameters</testCompilerArgument>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
有关详细信息,请参阅以下链接:
总结一下:
method.getParameterTypes()
为了为编辑器编写自动完成功能(如您在其中一个注释中所述),有几个选项:
arg0
arg1
arg2
intParam
stringParam
objectTypeParam