【问题标题】:How to determine the type of Object in java [closed]如何确定java中的对象类型[关闭]
【发布时间】:2020-09-16 13:16:49
【问题描述】:

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

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

【问题讨论】:

  • 你的意思是getClass()
  • 您可以将变量设为Optional 并与isPresent() 核对

标签: java java-8 java-stream


【解决方案1】:
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) …
【解决方案2】:

使用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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 2016-09-06
    • 2011-01-14
    相关资源
    最近更新 更多