我无法打印出方法factorial的注释。当我不使factorial返回任何值并将结果打印在方法本身时,它就可以工作。我不是在这里理解这个问题。
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();
}
}
}
答案 0 :(得分:3)
您必须指明参数的类型:
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)