import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
public class calculation {
static double pm10,pm2dot5,no2,o3,co,so2,nh3,pb;
static HashMap<String, Double> concentration;
static HashMap<String, Double> subIndex;
static Scanner sc ;
public static HashMap<Integer, Integer> _pm10,_pm2dot5,_no2,_o3,_so2,_nh3;
public static HashMap<Integer, Double> _co,_pb;
public static void main(String[] args) {
indexCalculation();
}
static void indexCalculation () throws NoSuchFieldException, SecurityException
{
Iterator<String> gases = concentration.keySet().iterator();
while(gases.hasNext())
{
String gas = gases.next();
double value = concentration.get(gas);
String str = "_"+gas;//this will create string instance like _so2,_nh3 etc..
Class obj = calculation.class;
Field field = obj.getField(str);
Iterator<Integer> breakpoint = field.keySet().iterator();//unable to do..
}
}
}
keySet()
方法就可以了。答案 0 :(得分:0)
您可以使用get
字段类方法来获取值。这是javadoc所说的内容:
返回此字段所代表的字段的值 指定的对象。如果,该值将自动包装在对象中 它有原始类型。
代码如下所示:
static void indexCalculation () throws Exception{
concentration = new HashMap<>(); //only for testing, remove this
concentration.put("so2", 10d); //only for testing, remove this
Iterator<String> gases = concentration.keySet().iterator();
while(gases.hasNext())
{
String gas = gases.next();
double value = concentration.get(gas);
String str = "_"+gas;//this will create string instance like _so2,_nh3 etc..
Class obj = calculation.class;
Field field = obj.getField(str);
Class<?> type = field.getType();
if(type == HashMap.class){
HashMap<Integer, Integer> map = (HashMap<Integer, Integer>) field.get(calculation.class);
System.out.println(map);
}
}
}
获得Map
后,您可以调用Map
界面的任何方法(例如keySet()
,get()
等)。
答案 1 :(得分:0)
您需要调用get(obj)
并将结果转换为正确的类。 Field
个实例只是对该字段的引用。调用get
需要一个对象来评估字段的值,请参阅the field class docs。