gpt4 book ai didi

java - 在运行时更改方法的行为?

转载 作者:行者123 更新时间:2023-12-01 15:12:43 26 4
gpt4 key购买 nike

我有以下代码。

一等

package com.test;

public class CustomizeHere
{
private CustomizeMe customizeMe = new CustomizeMe();
public void setDescription()
{
customizeMe.setText("How about calling some method before me?");
}
}

二等

package com.test;

public final class CustomizeMe
{
private String text = null;
public String getText()
{
return text;
}

public void setText(String text)
{
this.text = text;
}
}

三等

package com.test;

public class ReflectCustomizer
{
/**
* @param args
*/
public static void main(String[] args)
{
CustomizeHere customizeHere = new CustomizeHere();
// Requirement here is when customizeMe.setText() before method invocation we want to add some additional behaviour at run time like we should come to
// know setText() is invoked.
customizeHere.setDescription();
}
}

我想知道在上述场景中我是否可以知道正在调用 CustomizeMe 上的 setText() 方法?我无法从customizeMe更改代码,但我在运行时使用反射有customizeMe的实例。

我无法更改 CustomizeMeCustomizeHere 类中的代码。另外,由于 java.lang.Reflect.Method 类不允许附加任何监听器,因此我会知道它正在被调用,所以还有其他方法吗?

最佳答案

如果您的要求是在调用其他一些方法之前在对象上设置一些参数,则可以使用采用这些参数的构造函数,或者如果要创建的各种配置选项之间存在相互依赖关系,则可以遵循构建器模式。

关于java - 在运行时更改方法的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12107427/

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