Reputation: 495
I dont'know that, how can I read a file. I would like to read the FK.java file, but give me a class not found exception. FK is annotation java file. (I have tried "src/annotations/FK.java" but didn't work.
private static String clazz = "src/annotations/FK";
public static List<Object> GetAnnotations() throws ClassNotFoundException{
Class<?> c;
c = Class.forName(clazz);
List<Object> result = new ArrayList();
Field[] fields = c.getDeclaredFields();
for (int j = 0; j < fields.length; j++)
{
Annotation[] annot = fields[j].getAnnotations();
for (int k = 0; k < annot.length; k++)
{
result.add(annot[k].annotationType());
}
}
return result;
}
public static void main(String[] args) throws ClassNotFoundException {
System.out.println(GetAnnotations());
}
Upvotes: 0
Views: 823
Reputation: 5472
Your problem is, that you're trying to get the Class object for your annotated class with the wrong syntax.
The Class.forName(String)
-method takes a fully qualified Java class name as a parameter. That is the name of the package containing the class as declared in your Java-file immediately followed by your class name. In your case that is probably "annotations.FK"
.
An other note is that simply having the Java-source code file for the class will not do. You will need to have the compiled class in your classpath.
Here is a simple example:
// mytoplevelpackage/mypackage/MyClass.java
package mytoplevelpackage.mypackage;
public class MyClass {}
// mytoplevelpackage/OtherClass.java
package mytoplevelpackage;
public class OtherClass {
public static void main(String[] args) throws ClassNotFoundException {
Class c = Class.forName("mytoplevelpackage.mypackage.MyClass");
}
}
Upvotes: 0
Reputation: 28762
The name of the class should contain dots (.
) not slashes ('/
')
private static String clazz = "annotations.FK";
Then
Class.forName(clazz);
will try to load the class annotations/FK.class
from the provided classpath. If you only have the .java file, you will need to compile it first.
EDIT: fixed path based on comments
Upvotes: 1