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());
}
}
# 1 楼答案