[英]Is there any way to initialize variables from object and class names?(such as by using reflections)
例如:假設有一個Dog類,一個Dalmatian子類,而Dog類具有私有變量String name(品種); 現在我主要說:
Dog spot = new Dalamatian();
並自動獲得名稱=“ spot”,並繁殖=“ Dalmatian”。
很容易得到品種:
public class Dog {
private final String name;
private final String breed;
protected Dog(String name) {
// Default to using the class name
this(name, getClass().getSimpleName());
}
protected Dog(String name, String breed) {
// Allow subclasses to specify an explicit breed
this.name = name;
this.breed = breed;
}
}
我不相信Java中有任何方法可以推斷出spot
。 (您可以使用CallerMemberName
在C#中做到這一點,假設它是一個字段而不是局部變量。)
所以基本上你需要
Dog spot = new Dalmation("spot");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.