So,
I have a class called "GeraForm" that I need it to return a string in the HTML style form with some information contained in a note. I got the code to work when I pass a particular class to it, but I'd like the code, before returning the String, to create an instance of an object of the class so that, there, I could read the annotations of the methods of that class object and generate 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 believe is due to the lack of an object.
My annotation 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;
}
}