不通过方法名获取方法对象

3
有没有一种方法可以在不使用方法名的情况下获取一个方法对象?
例如,我有以下类:
class Car {

    public String drive();
    public String giveUp();
    public String fillUp();
}

我想创建一个方法的Map<String, Method>(例如:("move", drive()), ("name", giveUp()), ....)。
由于使用了混淆,我无法通过名称获取方法对象。是否有一种方法可以在不必绑定此方法的情况下获取方法名称?
我的意思是:
对于一个类,你有getClass(),那么方法有没有类似的东西?我正在寻找类似于giveUp.Method这样的东西。

2
尽管我很欣赏“混淆”拼错的讽刺意味,请尽量小心不要生成拼写错误的标签,特别是当你有自动完成功能可用时。 - skaffman
嘿,我把自动完成的错归咎于那个。 - monksy
1
嘿,为什么不排除混淆方法呢?即通过名称访问方法或进行混淆,这两个目标不能合并,通过绕过来实现是徒劳的。在最坏的情况下,创建一个if(key) { // call method for key } else if(nextKey) {...}。 - ThomasRS
2个回答

4

在Java中,没有像 Car.giveUp.method() 这样的结构,因为方法不像类和对象一样是“一等公民”。

如果不知道混淆器对代码的影响,或者添加额外信息,就无法区分这些方法,因为除了名称外,它们具有相同的签名。

  • Some obfuscators produce text files that map the original name to the obfuscated name, and you could use that map file to identify the obfuscated method at runtime.

  • You could add an annotation to the method, like

    @MappedMethod("move")
    public String drive();
    

    with a self-written annotation @MappedMethod and a default attribute of type String. Then use reflection to get all methods and their annotations, and use the annotation value as key.


3
你可以使用反射来获取所有的方法。
Class<Car> clazz = Car.class;
Method[] methods = clazz.getDeclaredMethods();

然后您可以迭代方法并将其映射:

for(Method method: methods)
    map.put( method.getName(), method);

我有特定的方法名称,我不需要映射所有的方法。目标是使用map.get("name").invoke(...)。由于混淆器的缘故,方法名将会发生变化。 - monksy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接