2
So,
I have a class called "Geraform" that I need to return a HTML-style string with some information contained in an annotation. I got the code to work when I pass a certain class to it, but I would like the code, before returning to String, to create an instance of a class object so that I could read the annotations of the methods of that object and generate the HTML form.
What happens is that when I get the value of the fields in the annotation, for example
String label = annotation.label();
I’m getting a nullPointerException, which I think is the lack of an object.
My note Campo.java:
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
@Target( { ElementType.METHOD } )
@Retention( RetentionPolicy.RUNTIME )
public @interface Campo {
int maxLength() default 0;
boolean required() default false;
String label();
}
My class Geraform.Java:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class GeraForm {
public String incluir(Class<?> formClass) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Class<?> wantedClass = formClass;
Method[] classMethods = wantedClass.getDeclaredMethods();
String methodName = "temp";
//I need to return a String in HTML form style at the and of the method
//Im gonna construct the string piece by piece to return at the end of the method
String returnString = "a";
//I get the name of the method and put it to lower case
for(int i=0; i < classMethods.length; i++) {
if(classMethods[i].getName().startsWith("set")) {
methodName = classMethods[i].getName().substring(3, classMethods[i].getName().length()).toLowerCase();
}
}
Campo annotation = classMethods[0].getAnnotation(Campo.class);
//Here I get the value of every field in the annotation
String label = annotation.label();
int maxLength = annotation.maxLength();
boolean required = annotation.required();
returnString = label+"<input type=\"text\" name=\""+methodName+"\"";
if(maxLength != 0) {
returnString = returnString +" maxlength=\""+maxLength+"\"";
}
if(required == true) {
returnString = returnString + " required=\"" + required + "\"";
}
returnString = returnString + ">";
return returnString;
}
}