我有這個規范,通過使用字串呼叫該變數的靜態實體來從特定類中獲取變數值。
假設我有一個名為 Sample 的類和另一個名為 testValue 的類。testValue 有一個公共靜態最終字串測驗,我必須列印它的值。當我嘗試以這種方式列印它時,輸出是“測驗值”。
public class Sample{
public static void main(String args[]){
System.out.println(testValue.test);
}
}
class testValue{
public static final String test = "Test Value";
}
現在我想通過其他字串呼叫它來列印“測驗值”。像這樣的東西:
public class Sample{
public static void main(String args[]){
String new = "test";
System.out.println(testValue.new);
}
}
class testValue{
public static final String test = "Test Value";
}
但這會產生錯誤,因為 new 沒有在 testValue 類中定義。有沒有其他方法可以做這件事。它有點奇怪,但這是我想要呼叫測驗變數的確切方式。提前致謝。
uj5u.com熱心網友回復:
您可能想要這樣做,因為它在 JavaScript 中作業。在Java中,你不能正常做這樣的事情。但是您可以使用反射,這是不推薦的獲取欄位值的方式:
public class TestClass {
public static final String field = "Test Value";
}
TestClass testClass = new TestClass();
Class<TestClass> personClass = TestClass.class;
Field field = personClass.getField("field");
String fieldValue = (String) field.get(testClass);
System.out.println(fieldValue);
uj5u.com熱心網友回復:
您可以在 testValue 類中為所需變數定義一個 getter
public class Sample{
public static void main(String args[]){
String new = testValue.getTest();
System.out.println(new);
}
}
class testValue{
public static String test = "Test Value";
public static String getTest(){
return test;
}
}
這將列印“測驗值”。為了不破壞封裝的最佳實踐,您還應該定義一個 setter 并使變數像這樣私有
public class Sample{
public static void main(String args[]){
String new = testValue.getTest();
System.out.println(new);
}
}
class testValue{
private static String test = "Test Value";
public static String getTest(){
return test;
}
public static void setTest(String test){
this.test = test;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/456716.html
