我有一个对象Field field
。
我想检查field
是Foo
类型的对象还是数组:Foo[]
。
Psuedo代码:
if field.getType() is Foo || field.getType is Foo[]
这可能吗?
我试过
if (field.getType().isArray())
// do something
但这只允许我检查field
是否为数组。
相反,这样做只会检查它是Foo
if (Foo.class.isAssignableFrom(field.getType())
// do something
知道怎么做吗?
感谢。
答案 0 :(得分:18)
以下是我曾经用过的一些代码来处理Java中所有原始类型的数组。由于它们不扩展Object类,因此检查Object []的实例是不够的。
/* Check if the given object is an array. */
if (object.getClass().isArray()) {
Class<?> componentType;
componentType = object.getClass().getComponentType();
if (componentType.isPrimitive()) {
if (boolean.class.isAssignableFrom(componentType)) {
for (boolean anElement : (boolean[]) object) {
/* ... */
}
}
else if (byte.class.isAssignableFrom(componentType)) {
/* ... */
}
else if (char.class.isAssignableFrom(componentType)) {
/* ... */
}
else if (double.class.isAssignableFrom(componentType)) {
/* ... */
}
else if (float.class.isAssignableFrom(componentType)) {
/* ... */
}
else if (int.class.isAssignableFrom(componentType)) {
/* ... */
}
else if (long.class.isAssignableFrom(componentType)) {
/* ... */
}
else if (short.class.isAssignableFrom(componentType)) {
/* ... */
}
/* No else. No other primitive types exist. */
}
else {
/* Do something with Object[] here. */
}
}
答案 1 :(得分:2)
假设你提到的字段是java.lang.reflect.Field
,你可以做
field.getType().equals(Foo.class) || field.getType().equals(Foo[].class)
答案 2 :(得分:2)
简单比较应该有效
import java.lang.reflect.Field;
public class Main {
String[] myStringArray;
String[] myStringArray2;
Object[] myObjectArray;
String str;
public static void main(String... args) {
Field[] flds = Main.class.getDeclaredFields();
for (Field f : flds) {
Class<?> c = f.getType();
if (c == String[].class) {
System.out.println("field" + f.getName() + " is String[]");
}
if (c == String.class) {
System.out.println("field" + f.getName() + " is String");
}
if (c == Object[].class) {
System.out.println("field" + f.getName() + " is Object[]");
}
}
}
}
答案 3 :(得分:0)
if (field instanceof Object[])
应该这样做。
答案 4 :(得分:0)
由于数组类型已确定,因此您只需使用
即可if ( field.getType() == Foo.class || field.getType() == Foo[].class ) {
}
完整示例:
public class Scratchpad {
String[] strings;
public static void main(String[] args) throws NoSuchFieldException {
if (Scratchpad.class.getDeclaredField("strings").getType() == String[].class) {
System.out.println("They're Strings!");
}
if (Scratchpad.class.getDeclaredField("strings").getType() == Long[].class) {
System.out.println("They're Longs!");
}
}
}
答案 5 :(得分:0)
我会做这样的事情:
public static void main(String[] args) {
Foo foo = new Foo();
Foo[] other = new Foo[1];
other[0] = new Foo();
System.out.println(isFooOrArrayOfFoo(foo));
System.out.println(isFooOrArrayOfFoo(other[0]));
System.out.println(isFooOrArrayOfFoo(new Object()));
}
private static boolean isFooOrArrayOfFoo(Object o) {
return (o instanceof Foo || o.getClass().equals(Foo.class) && o.getClass().isArray());
}