![](/img/trans.png)
[英]Is there any way to get around a class not implementing Serializable?
[英]Is there any way to generate code in Interface on implementing it in a class
我想將類的getter和setter的所有摘要添加到我在該特定接口中實現的接口。 我還想生成一個類似於類變量的最終變量。 反序列化后,此變量可以用作訪問類變量的字符串。
例如:
public class Abc implements IAbc{
private String oneVariable;
public String getOneVariable(){
return oneVariable;
}
}
使用接口IAbc實現上述類。 IAbc應該包含以下代碼:
public interface IAbc{
public static final String ONE_VARIABLE = "oneVariable";
public getOneVariable();
}
我曾嘗試使用Google搜索解決方案,但沒有得到任何解決方案。 同樣,在生成此代碼之后,類中的方法還應具有@Override批注。
TL; DR這是一個有趣的編程挑戰,但是我發現在現實生活中它很少使用。
在這里,第一個字符串變量的名稱是事先已知的,您可以直接在其中存儲最終值,而不是用second回的方式存儲第二個變量的名稱。
如果理解正確,您正在嘗試訪問其名稱將在另一個字符串變量中的類的(字符串)變量。 使用java反射可以做到這一點。
另外,您希望將此代碼放置在接口中,以便可以在實現它的所有類中(重新)使用它。
import java.lang.reflect.Field;
interface Foo {
public default String getStringVar()
throws NoSuchFieldException, IllegalAccessException {
// get varName
Class thisCls = this.getClass();
Field varNameField = thisCls.getField("varName");
String varName = (String) varNameField.get(this);
// get String variable of name `varName`
Field strField = thisCls.getField(varName);
String value = (String) strField.get(this);
return value;
}
}
class FooImpl1 implements Foo {
public final String varName = "str1";
public String str1 = "some value";
}
class FooImpl2 implements Foo {
public final String varName = "str2";
public String str2 = "some other value";
}
class Main {
public static void main(String[] args)
throws NoSuchFieldException, IllegalAccessException {
System.out.println(new FooImpl1().getStringVar());
System.out.println(new FooImpl2().getStringVar());
}
}
在這里,我在實現接口Foo
類中有兩個String成員。 第一個varName
包含第二個String的變量名,第二個String變量包含數據。
在使用反射的接口中,我首先提取存儲在varName
的變量名稱,然后使用此方法提取第二個String的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.