如何在java中确定对象的类型

如何在java中确定对象的类型,java,java-8,java-stream,Java,Java 8,Java Stream,我有一个类a,它包含其他类B,C,D作为变量。在任何时间点,类A都将填充B、C、D 我们如何使用streams/map来确定存在的对象的类型并将其返回给调用者?使用reflect来获取所有字段,然后确定您想要什么 公共A类{ 私有整数a; 私有字符串b; 公共静态无效字符串[]args{ A对象=新的A对象; 字段[]字段=A.class.getDeclaredFields; Arrays.streamfields.mapField::getName.forEachSystem.out::pri

我有一个类a,它包含其他类B,C,D作为变量。在任何时间点,类A都将填充B、C、D

我们如何使用streams/map来确定存在的对象的类型并将其返回给调用者?

使用reflect来获取所有字段,然后确定您想要什么

公共A类{ 私有整数a; 私有字符串b; 公共静态无效字符串[]args{ A对象=新的A对象; 字段[]字段=A.class.getDeclaredFields; Arrays.streamfields.mapField::getName.forEachSystem.out::println; } }
你是说getClass?你可以选择变量,然后用iPresentVery像样的答案进行检查!或返回Stream.ofb,c,d.filterObject::非空…
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());
    }
}