英文:
How to determine the type of Object in java
问题
我有一个类(A),其中包含其他类B、C、D作为变量。在任何时刻,类A要么有B、C、D填充在其中。
我们如何使用流/映射来确定存在的对象类型并将其返回给调用者?
英文:
I have a class (A) which contains other classes B,C,D as variables . At any point of time class A will either have B,C,D populated in it.
How can we use streams/map to determine the kind of object present and return it to caller ?
答案1
得分: 1
使用 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);
}
}
英文:
use reflect
to get all fields and then do want you want
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);
}
}
答案2
得分: 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());
}
}
英文:
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());
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论