Accessing Field Variable from Generic Object

拥有回忆 提交于 2020-01-24 16:32:39

问题


I have two classes, ClassOne and ClassTwo, that update a public field data i.e.,

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, i.e., the app detects the source of the data at run time and uses either ClassOne or ClassTwo. 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.

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? 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.


回答1:


Create an interface DataProvider with a method getData() which returns your data field. Then in your class ParseMyData<T> you will write instead 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. But I'd recommend you to go with the first option.



来源:https://stackoverflow.com/questions/19494817/accessing-field-variable-from-generic-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!