James B
James B

Reputation: 9605

Accessing Field Variable from Generic Object

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.

Upvotes: 2

Views: 2606

Answers (1)

noone
noone

Reputation: 19776

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.

Upvotes: 4

Related Questions