gpt4 book ai didi

java - 默认覆盖处理程序

转载 作者:行者123 更新时间:2023-11-30 09:32:03 25 4
gpt4 key购买 nike

有没有一种方法可以定义一个默认的或回退的覆盖方法来处理任何未处理的方法?

我问这个的原因是因为我创建了一个类来覆盖函数库中不断变化的类。为了成功编译该类,必须定义和覆盖所有方法,但我真的不想每次有更新时都重新编码我的类。

下面是一个例子:

public class CommandSignsPlayerProxy implements Player {

private Player proxy;
private boolean silent;

public CommandSignsPlayerProxy(Player targetPlayer) {
this.proxy = targetPlayer;
}

public boolean isSilent() {
return silent;
}

public void setSilent(boolean silent) {
this.silent = silent;
}

@Override
public void abandonConversation(Conversation conversation, ConversationAbandonedEvent details) {
proxy.abandonConversation(conversation, details);
}

// This function is basically the only one that NEEDS overriding
@Override
public void sendMessage(String message) {
if (!silent)
proxy.sendMessage(message);
}

@Override
public void setFlySpeed(float arg0) throws IllegalArgumentException {
proxy.setFlySpeed(arg0);
}

}

在实际代码中,还有另外 50 多个重写函数。那么有没有办法制作一个自动处理程序,用 proxy.function_name() 覆盖 function_name()

最佳答案

A Dynamic Proxy也许能够做到这一点。来自文档:

A dynamic proxy class is a class that implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface. Thus, a dynamic proxy class can be used to create a type-safe proxy object for a list of interfaces without requiring pre-generation of the proxy class, such as with compile-time tools.

Method invocations on an instance of a dynamic proxy class are dispatched to a single method in the instance's invocation handler, and they are encoded with a java.lang.reflect.Method object identifying the method that was invoked and an array of type Object containing the arguments.

关于java - 默认覆盖处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12646823/

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