java读取类的方法并在arraylist中存储Web服务的路径名
ArrayList<String> list = new ArrayList<String>();
try
{
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"))
{
String app = Vtiger_Services.class.getDeclaredMethods()[i].getName();
list.add(app);
//se non sono uguali li aggiungo
con.createStatement().execute("INSERT INTO Services (Name) VALUES ('"+ Vtiger_Services.class.getDeclaredMethods()[i].getName()+"')");//popolo la tabella services
}
}
}
System.out.println(list);
}
我的类Vtiger services包含应用程序的web服务,我想获取类中存在的每个web服务的名称和路径名
通过这种方式,我可以得到每个人的名字,但我无法在arraylist中记住路径名
String app = Vtiger_Services.class.getDeclaredMethods()[i].getName();
在variable app中,我想存储每个Web服务的路径名
Vtiger_类服务:
public class Vtiger_Services{ `@Path("getCustomer/{code : .+}")
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getCustomer(@HeaderParam("token") String token, @PathParam("code") int code) // il codice cliente è un intero
{
if (token.equalsIgnoreCase(this.token)) {
String sql = "select .......";
// System.out.println(sql);
Database db = new Database();
String json = db.executeQueryTOJSON(sql);
// System.out.println(json);
return json;
} else
return "{\"error\":\"bad token provided or customer code\"}";
}
我想获取getCustomer方法的路径,并将字符串存储在arraylist中
# 1 楼答案
由于不知道您使用什么技术/框架来公开使用HTTP作为端点、映射到URL路径的服务,我无法回答您的问题。不过,我会尝试给出一个大致的方向:
您必须自己实现URL路径映射,以使用方法名称构造路径,或者需要访问web服务框架映射状态,以从中提取URL路径
Java反射非常昂贵/缓慢,因此您应该只调用以下方法一次,将返回值赋给一个变量,然后使用该变量(重构->;提取变量)编辑:有关部分实现,请参阅jacq_42答案:
如果您编写的代码应该定期运行,那么您可能希望用插入或更新的内容替换insert语句。稍后,您很可能还需要删除不再存在的web服务条目(有人从Vtiger_Services类中删除了一个方法)
永远不要使用字符串连接创建SQL语句,使用参数化语句(https://www.owasp.org/index.php/Query_Parameterization_Cheat_Sheet)。在您的示例中,您添加到查询的不是用户输入,因此不存在安全风险。由于一个方法名很可能永远不会包含一个引号,所以你也可以使用引号,所以从理论上讲,你可以这样构建你的语句,并且是安全的。但情况并非总是如此,最终您将构建一些易受SQL注入攻击的东西。如果您感兴趣,它将被列为web应用程序的十大安全风险:https://www.owasp.org/index.php/SQL_Injection
我希望这对你的旅程有所帮助:)
编辑: 因为您需要@Path注释的值,所以应该能够使用getAnnotation获得路径:
annotation
引用应该为您提供获取路径的方法您应该认真检查SQL注入攻击,因为
看起来很危险