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