i've a class call Vtiger_Services in which I have a lot of web services methods... I want to get the annotation of every web services and store it as a string in arraylist
example web services in Vtiger_Services:
@Path("getCustomers")
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getCustomers(@HeaderParam("token") String token) {
if (token.equalsIgnoreCase(this.token)) {
String sql = "select * from tab1";
Database db = new Database();
String json = db.executeQueryTOJSON(sql);
return json;
} else
return "{\"error\":\"bad token provided\"}";
}
I want to get the vaule of @Path
I made this method to get the name
for(int i = 0; i < Vtiger_Services.class.getMethods().length; i++)
{
if(Vtiger_Services.class.getMethods()[i].getParameters().length > 0 &&
Vtiger_Services.class.getMethods()[i].getParameters()[0].getType().getSimpleName().equals("String") &&
Vtiger_Services.class.getMethods()[i].getReturnType().getSimpleName().equals("String"))
{
con.createStatement().execute("INSERT INTO Services (Name) VALUES ('"+ Vtiger_Services.class.getDeclaredMethods()[i].getName()+"')");
}
}
You may use java refection to get classes methods and then look for annotations on these methods.
public class Test {
@Path("getCustomers")
public void test() {
}
public static List<String> getMethodsAnnotatedWith(final Class<?> type) {
final List<String> paths = Lists.newArrayList();
Class<?> clazz = type;
while (clazz != Object.class) {
final List<Method> allMethods = new ArrayList<>(Arrays.asList(clazz.getDeclaredMethods()));
for (final Method method : allMethods) {
Path path = method.getAnnotation(Path.class);
if(path != null) {
paths.add(path.value());
}
}
// move to the upper class in the hierarchy in search for more methods
clazz = clazz.getSuperclass();
}
return paths;
}
public static void main(String[] args) {
System.out.println(getMethodsAnnotatedWith(Test.class));
}
}