如何从另一个Java类中动态访问静态变量?
Hey there! Let's work through this problem where you can access your DummyData static variables directly (like DummyData.Survey_1) but can't get their values using a dynamic string variable (like data).
Java is a statically typed language, so it doesn't natively support accessing fields by a runtime-generated string out of the box. But we've got two solid approaches to fix this:
1. Use Java Reflection API
If you want to keep your existing DummyData class structure as-is, reflection lets you dynamically look up and access static fields at runtime. Here's how to implement it:
First, add a helper method to your DummyData class to handle the reflection logic:
import java.lang.reflect.Field; public class DummyData { public static String Survey_1 = "Your Survey 1 content"; public static String Survey_2 = "Your Survey 2 content"; public static String Survey_3 = "Your Survey 3 content"; // Helper method to fetch static field value dynamically public static String getDynamicSurveyValue(String fieldName) { try { // Get the public static field by name from DummyData class Field targetField = DummyData.class.getField(fieldName); // For static fields, pass null as the object instance parameter return (String) targetField.get(null); } catch (NoSuchFieldException e) { System.err.println("Field '" + fieldName + "' doesn't exist in DummyData"); return null; } catch (IllegalAccessException e) { System.err.println("No permission to access field '" + fieldName + "'"); return null; } } }
How to use it:
When you have your dynamic variable data (e.g., data = "Survey_1"), just call:
String surveyValue = DummyData.getDynamicSurveyValue(data);
Note: Reflection relies on exact field name matches (case-sensitive!), and only works with public fields (which your variables already are).
2. Use a Map for Storing Survey Data (Recommended)
If you're open to adjusting your class structure, using a Map to store your survey values is cleaner, type-safe, and avoids the complexity of reflection. It's also easier to maintain if you add more survey variables later.
Here's the refactored DummyData class:
import java.util.HashMap; import java.util.Map; public class DummyData { // Store all survey values in a static Map private static final Map<String, String> SURVEY_MAP = new HashMap<>(); // Initialize the Map in a static block static { SURVEY_MAP.put("Survey_1", "Your Survey 1 content"); SURVEY_MAP.put("Survey_2", "Your Survey 2 content"); SURVEY_MAP.put("Survey_3", "Your Survey 3 content"); } // Optional: Keep your original static variables for backward compatibility public static String Survey_1 = SURVEY_MAP.get("Survey_1"); public static String Survey_2 = SURVEY_MAP.get("Survey_2"); public static String Survey_3 = SURVEY_MAP.get("Survey_3"); // Helper method to fetch values dynamically public static String getDynamicSurveyValue(String key) { // Return null if key doesn't exist, or use getOrDefault for a default value return SURVEY_MAP.get(key); // Example with default value: return SURVEY_MAP.getOrDefault(key, "No data found"); } }
How to use it:
Same as the reflection approach—just pass your dynamic data variable to the helper method:
String surveyValue = DummyData.getDynamicSurveyValue(data);
Bonus: If you ever need to update a survey value, update the Map first and sync the static variable (or just use the Map directly) to avoid data inconsistency.
Which one should you choose?
- Use reflection if you can't modify the existing structure of
DummyDataor need to keep direct static variable access without changes. - Use the Map approach if you want a more maintainable, readable solution with no reflection overhead.
内容的提问来源于stack exchange,提问作者AsifAli

