我试图通过使用Class.forname从Android设备获取屏幕大小。 我试图获得的变量是widthPixels& heightPixels,但我收到错误
" 预期的android.util.DisplayMetrics类型的接收器,但得到了java.lang.reflect.Field "
这是我的代码:
public Object field;
public String getInstanceValue(String classInstance, String fieldName) {
try {
Class Build1 = Class.forName(classInstance);
Field strField = Build1.getDeclaredField(fieldName);
strField.setAccessible(true);
field = strField.get(strField);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return field.toString();
}
这是班级:
package android.util;
public class DisplayMetrics {
public static final int DENSITY_LOW = 120;
public static final int DENSITY_MEDIUM = 160;
public static final int DENSITY_TV = 213;
public static final int DENSITY_HIGH = 240;
public static final int DENSITY_XHIGH = 320;
public static final int DENSITY_400 = 400;
public static final int DENSITY_XXHIGH = 480;
public static final int DENSITY_XXXHIGH = 640;
public static final int DENSITY_DEFAULT = 160;
public int widthPixels;
public int heightPixels;
public float density;
public int densityDpi;
public float scaledDensity;
public float xdpi;
public float ydpi;
public DisplayMetrics() {
throw new RuntimeException("Stub!");
}
public void setTo(DisplayMetrics o) {
throw new RuntimeException("Stub!");
}
public void setToDefaults() {
throw new RuntimeException("Stub!");
}
public boolean equals(Object o) {
throw new RuntimeException("Stub!");
}
public boolean equals(DisplayMetrics other) {
throw new RuntimeException("Stub!");
}
public int hashCode() {
throw new RuntimeException("Stub!");
}
public String toString() {
throw new RuntimeException("Stub!");
}
}
android.view.Display类也有方法getMetrics,
public void getMetrics(DisplayMetrics outMetrics) {
throw new RuntimeException("Stub!");
}
Plz帮助:)
答案 0 :(得分:0)
你应该做
Class Build1 = classInstance.getClass();
Field strField = Build1.getDeclaredField(fieldName);
//strField.setAccessible(true); No need as all variables are public
field = strField.get(classInstance); //use classInstance instead of strField
此外,您还必须将方法更改为
public String getInstanceValue(DisplayMetrics classInstance, String fieldName)