Java 注释 : Method cannot be found via reflection

标签 java annotations

我无法打印出方法阶乘的注释。当我不让阶乘返回任何值并在方法本身中打印结果时,它就可以工作了。我不明白这里的问题。

import java.io.*;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;

@Retention(RetentionPolicy.RUNTIME)

@interface Store
{
int id();
String developerName();
String createdDate();
String Copyrightmessage();
}

public class Ch10LU1Ex2 
{
@Store(id = 1, developerName = "Robin", createdDate = "03/Jan/2013", Copyrightmessage =     "Cannot copy anything")
public static int factorial(int n)
{
    int result;
    if(n==1)
    return 1;
    result = factorial(n-1) * n ;
    return result;

}

public static void main(String[] args) 
{
    try
     {


      Ch10LU1Ex2 ch = new Ch10LU1Ex2();
      System.out.println("Enter any number from 0 to 10 to find factorial:");
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      int ch1 = Integer.parseInt(br.readLine());
      int x = ch.factorial(ch1);
      System.out.println("The factorial is:"+x);
      Method method = ch.getClass().getMethod("factorial");
      Annotation[] annos = method.getAnnotations();
      for(int i=0; i<annos.length;i++)
      {
        System.out.println(annos[i]);
      }
     }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}
}   

最佳答案

您必须指明参数的类型:

Method method = Ch10LU1Ex2.class.getMethod("factorial", Integer.TYPE);

否则你只会得到一个NoSuchMethodException

这是我为“1”得到的输出:

Enter any number from 0 to 10 to find factorial:
1
The factorial is:1
@Store(id=1, developerName=Robin, createdDate=03/Jan/2013, 
Copyrightmessage=Cannot copy anything)

关于Java 注释 : Method cannot be found via reflection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14144590/

相关文章:

ios - 设置 Core-Plot 注释区域

ios - 调整 MkMapView 注解

java - 在JVM之外获取音频级别

Java-同步列表

如果不满足条件则忽略方法调用的 Java 注释

java - @Resource 注释由 spring 和应用程序服务器拾取

java - 如何确保 Xtend Activity 注释处理器生成的 java 输出中包含所需的导入?

java - Maven 部署文件目标 : Why does the first execution interfere with the second one?

java - Spring 启动 : Cannot change version of project facet to 3. 1

java - 将字符串拆分为矩阵或表格并存储到 ArrayList 中