gpt4 book ai didi

java - 在运行时添加依赖于同一类中带有注释的方法的方法

转载 作者:行者123 更新时间:2023-12-02 07:08:56 25 4
gpt4 key购买 nike

目前我的监听器需要一个切换树来调用内部方法。

public class Car{


public void listener(String e){
if(e.equals("Honk"))
this.blowHorn();
}

@Honk
private void blowHorn(){...}

}

是否可以利用反射和方法注释,以便在运行时生成监听器方法?它将根据输入是否等于方法注释进行切换。这比使用普通反射更好,因为它减少了开销。

最佳答案

************************反射(reflection)回答************************

首先,您将声明新注释,如下所示:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CarListener{
public String carAction();
}

这样在你的 Car 类中你将拥有:

public class Car {

//Here you´ll be looking at all the methods you have in the class Car (I´d advice to
// put them in another class, so as to keep it clean, I didn´t do it here in order to
// explain it better. These methods have the corresponding annotation you created

public void listener(String e) {
Method[] methods = Car.class.getMethods();
for(Method method:methods) {

//Now that you have all the methods all you need is to figure which one you want
// you´ll do that according to the "e" string, which represents the car action (for
// example "Honk") I´d also advice you to rename that too.

if(rightMethod(method, e))

//Now that you have found it, then you invoke the method, "call it"
// which is what you wre doing in the previos code with "this.blowHorn()"

return invokeMethod(method);
}
//This will help you in case you did NOT find the correct method, it´s just help
// if you don´t put it in it won´t break your code
// fun fact about RuntimExceptions: you don´t have to declare them, meaning
// you dont have to add them as "throws" or catch

throw new RuntimeException("No listener found for car Action"+e);
}

private boolean rightMethod(Method method, String expression) {

//First if asks if the method found has an annoation present, and if it does
// then it asks if it corresponds to the annoation you created

if (method.isAnnotationPresent(NewAnnotationInterfaceName.class))

//if the method in fact has the annotation created all you are doing is asking what
// carAction is associated to that method, you do that with the .carAction()

return method.getAnnotation(NewAnnotationInterfaceName.class).carAction().equals(expression);
return false;
}


//Now all you have to do is invoke it :) This just follows how to invoke a method
// I won´t explain it

private void invokeMethod(Method method) {
try {
return method.invoke(Car.class.newInstance(), new Object[]{});
} catch (InstantiationException | IllegalAccessException
| InvocationTargetException | IllegalArgumentException ex) {
Logger.getLogger(Car.class.getName()).log(Level.SEVERE, null, ex);
}
throw new RuntimeException("Could not invoke method");
}


@CarListener(carAction= "Honk")
public void blowHorn() {
...
}

@CarListener(carAction= "SomethingElse")
public void someOtherAction() {
...
}

}

希望有帮助!

************************用 HashMap 和命令设计来回答******************** ***

public abstract class CarAction {

public abstract void execute(Car car){};

}

public class HonkAction extends CarAction{

@Override
public void execute(Car car) {
car.blowHorn();
}

}

public class Car {

private HashMap<String, CarAction> carActions;

public Car() {
...
initializeCarActions();
}

public void initializeCarActions() {
this.carActions = new HashMap<>();
this.carActions.put("Honk", new HonkAction());
...
}

public void listener(String e) {
CarAction action = this.carActions.get(e);
if(action!=null) action.execute(this);
}

}

如果你要使用这种方式,我建议有人注入(inject) HashMap,这样 Car 就不必依赖于 CarActions(只是抽象类),要么使用一个类,要么使用 Guice。此外,如果所有 carActions 只需要“Car”即可执行,则此方法有效。

祝你好运!

关于java - 在运行时添加依赖于同一类中带有注释的方法的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15773540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com