简体   繁体   English

从通用对象访问字段变量

[英]Accessing Field Variable from Generic Object

I have two classes, ClassOne and ClassTwo , that update a public field data ie, 我有两个类, ClassOneClassTwo ,它们更新公共字段data

public class ClassOne {
    public byte[] data = new byte[10];

    // Thread that updates data

}

and

public class ClassTwo {
    public byte[] data = new byte[10];

    // Thread that updates data

}

Only one class and its associated thread is running at any given time, ie, the app detects the source of the data at run time and uses either ClassOne or ClassTwo . 在任何给定时间,只有一个类及其相关线程正在运行,即,该应用在运行时检测到数据源并使用ClassOneClassTwo I want to parse the data in a separate class called ParseMyData , but a little confused as to the best way to set this up so ParseMyData can access data from either ClassOne or ClassTwo . 我想在一个名为ParseMyData的单独类中解析数据,但是对于设置ParseMyData的最佳方法有些困惑,因此ParseMyData可以从ClassOneClassTwo访问data

I'm currently trying to do it using generics, something like: 我目前正在尝试使用泛型,例如:

public class ParseMyData<T> {

    T classOneOrClassTwo;

    ParseMyData(T t) {
        classOneOrClassTwo = t;
    }

    public void parseIt() {
        // Need to access data from either ClassOne or ClassTwo here, something like:
        classOneOrClassTwo.data; // this obviously doesn't work
    }

So my question is how do I access the field data from within the class ParseMyData ? 所以我的问题是如何从ParseMyData类中访问字段data Do I have to use reflection? 我必须使用反射吗? Is reflection the only and best method to use? 反射是唯一,最佳的使用方法吗?

New to generics and reflection, so thoughts and pointers greatly appreciated. 泛型和反射的新手,所以思想和指针大为赞赏。

Create an interface DataProvider with a method getData() which returns your data field. 使用方法getData()创建一个接口DataProvider ,该方法返回您的data字段。 Then in your class ParseMyData<T> you will write instead ParseMyData<T extends DataProvider> . 然后在类ParseMyData<T>您将编写ParseMyData<T extends DataProvider>

public class ParseMyData<T extends DataProvider> {

    T classOneOrClassTwo;

    ParseMyData(T t) {
        classOneOrClassTwo = t;
    }

    public void parseIt() {
        classOneOrClassTwo.getData();
    }

Alternatively you might also use your version, but do an instanceof check first and then cast to either ClassOne or ClassTwo . 或者,您也可以使用您的版本,但先执行instanceof检查,然后将其ClassOne转换为ClassOneClassTwo But I'd recommend you to go with the first option. 但我建议您选择第一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM