【发布时间】:2015-11-19 07:29:36
【问题描述】:
我正在尝试使用 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!");
}
请帮忙:)
【问题讨论】:
-
“错误”是 java 运行时异常还是编译时错误?
-
这行不通。即使使用反射,您也需要一个 instance 而不是 class 来检索实例变量。请仔细阅读
Field.get(Object)documentation(https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#get-java.lang.Object-). Also nice to read: [The Reflection API。 -
是的,看来您需要将 classInstance 而不是 strField 传递给 get 方法
-
另外,变量名
classInstance是个惨不忍睹的选择。这显然是为了识别 class 而不是 instance。 -
我上面的链接有些放错了...再试一次:1)
Field.get(Object)documentation。 2)The Reflecion API.