【发布时间】:2020-09-16 13:16:49
【问题描述】:
我有一个类 (A),其中包含其他类 B、C、D 作为变量。在任何时间点,A 类都将填充 B、C、D。
我们如何使用流/映射来确定存在的对象类型并将其返回给调用者?
【问题讨论】:
-
你的意思是
getClass()? -
您可以将变量设为
Optional并与isPresent()核对
标签: java java-8 java-stream
我有一个类 (A),其中包含其他类 B、C、D 作为变量。在任何时间点,A 类都将填充 B、C、D。
我们如何使用流/映射来确定存在的对象类型并将其返回给调用者?
【问题讨论】:
getClass()?
Optional 并与isPresent() 核对
标签: java java-8 java-stream
import java.util.Arrays;
public class A {
public static class B {}
public static class C {}
public static class D {}
B b;
C c;
D d;
public A(B b, C c, D d) {
this.b = b;
this.c = c;
this.d = d;
}
public Class<?> getValueType() {
A me=this;
try {
return Arrays.stream(this.getClass().getDeclaredFields()).filter(field->{
try {
return field.get(me)!=null;
} catch (IllegalArgumentException | IllegalAccessException e) {
return false;
}
}).findAny().get().get(me).getClass();
} catch (IllegalArgumentException | IllegalAccessException | SecurityException e) {
e.printStackTrace();
return null;
}
}
public static void main(String args[])
{
System.out.println(new A(new B(),null,null).getValueType());
System.out.println(new A(null,new C(),null).getValueType());
System.out.println(new A(null,null,new D()).getValueType());
}
}
【讨论】:
return Stream.of(b, c, d).filter(Object::nonNull) …
使用reflect 获取所有字段,然后做你想要的
public class A {
private Integer a;
private String b;
public static void main(String[] args) {
A aobject = new A();
Field[] fields = A.class.getDeclaredFields();
Arrays.stream(fields).map(Field::getName).forEach(System.out::println);
}
}
【讨论】: