![](/img/trans.png)
[英]How can I change an Object instance and return a value from in the same method?
[英]Change return value of an instance method
我想從實例 class 調整方法的返回值,我不太確定是否可以使用或不使用反射。 我想不通,所以我想在這里問。 假設我有例如以下 class Foo:
public final class Foo {
public final String getName() {
return "Foo";
}
}
一些上下文:
因此,對於這個基本示例,我想從方法 getName() 而不是Foo返回Bar 。 要非常明確:
Foo foo = new Foo();
String name = foo.getName();
System.out.println(name) //prints "Bar"
為什么我需要這個?
好吧,我需要將此 Foo 實例傳遞給另一個只接受 Foo 類型的 object 的方法。 此方法將調用方法 getName() 並進行一些額外的計算。
實際用例:
我將嘗試提供更多上下文,希望它會更清楚一點。 構建器 class 中有一個方法,它接受KeyManagerFactory
的實例,該方法稱為setKeyManagerFactory(KeyManagerFactory keyManagerFactory)
。 此構建器 class 將在內部調用 KeyManagerFactory 上的getKeyManagers
並將返回KeyManagers[]
KeyManagerFactory 是最終的 class,它根本沒有公共構造函數。 getKeyManager 方法也是最終的。 我已經有一個KeyManager[]
,所以我想破解這個 KeyManagerFactory 以返回我自己的數組自己的 KeyManagers 並將其提供給構建器。
由於您說初始 class 是最終的並且無法實例化,因此您無能為力。
根據我從這個問題的理解,有可能創建一個新的 class ,其中包含一個Foo
object 及其所有方法。 然后當您從新創建的Bar
class 調用方法時,您可以在父級上調用相同的 function。 當然,當涉及到您的getName
function 時除外。
public final class Foo {
public String getName() {
return "Foo";
}
public String getBiz() {
return "Biz";
}
}
public class Bar {
private Foo foo;
public Bar() {
this.foo = new Foo();
}
public String getName() {
return "Bar";
}
public String getBiz() {
return this.foo.getBiz();
}
}
Bar bar = new Bar();
String name = bar.getName();
System.out.println(name) //prints "Bar"
String biz = bar.getBiz();
System.out.println(biz) //prints "Biz"
Notice here that the getBiz
function of the bar
object is only calling the getBiz
function of the Foo
object, not changing it's return value.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.