gpt4 book ai didi

Java反射获取未知类型子类的声明字段

转载 作者:行者123 更新时间:2023-12-01 13:19:12 24 4
gpt4 key购买 nike

我正在编写一个数据包类,希望能够获取其子类的所有声明字段,将它们添加到列表中,然后通过网络发送它们。

数据包父类(super class):

public class TCPacket {
private PacketType packetType;
private List<Object> packetData = new ArrayList<Object>();

public TCPacket(PacketType type){
this.packetType = type;
packetData.add(type.getIdent());
}

public PacketType getType(){
return packetType;
}

public List<Object> getDataList(){
return packetData;
}

public ByteArrayOutputStream getDataOS() throws IOException{
//writes data to stream
}

public void addData(Object object){
this.packetData.add(object);
}

private void addDeclaredFields(){
Field[] fields = this.getClass().asSubclass(this.getClass()).getDeclaredFields();

for(Field field : fields)
this.packetData.add(field);
}
}

其中重要的一行是:

Field[] fields = this.getClass().asSubclass(this.getClass()).getDeclaredFields();

我的希望是,通过这个,我将能够仅获取子类的所有声明字段,无论子类类型如何。

显然我可以做这样的事情:

Field[] fields = this.getClass().asSubclass(PacketRequestLogon.class).getDeclaredFields();

但我不想对每种数据包类型进行硬编码。我真正要问的是,如果包含子类的方法:从父类(super class)中调用 addDeclaredFields() , this.getClass() 是否会返回子类,或者它是否会返回 super 。

最佳答案

My hope, is that with this, i will be able to get all the declared fields of the SubClass ONLY, regardless of the SubClass type.

来自Class#getDeclaredFields jadavoc(强调我的):

Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private fields, but excludes inherited fields.

因此您可以确定您没有从父类(super class)获取字段。

<小时/>

测试了您当前的 addDeclaredFields 实现:

class ASuperClass {
protected int fieldInASuperClass;
public final void addDeclaredFields(){
Field[] fields = this.getClass().asSubclass(this.getClass()).getDeclaredFields();
for(Field field : fields) {
//edited this line for test purposes
System.out.println(field.getName());
}
}
}

class ASubClass extends ASuperClass {
private int fieldInASubClass;
}

class AnotherSubClass extends ASuperClass {
private int fieldInAnotherSubClass;
private int justAnotherFieldInAnotherSubClass;
}

public class AMainClass {
public static void main(String[] args) {
new ASuperClass().addDeclaredFields();
System.out.println("--------------------------------------");
new ASubClass().addDeclaredFields();
System.out.println("--------------------------------------");
new AnotherSubClass().addDeclaredFields();
}
}

打印:

fieldInASuperClass
--------------------------------------
fieldInASubClass
--------------------------------------
fieldInAnotherSubClass
justAnotherFieldInAnotherSubClass

注意,只打印子类声明的字段,继承的字段不会打印。

关于Java反射获取未知类型子类的声明字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22182599/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com