2

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.

James B
  • 8,975
  • 13
  • 45
  • 83
  • Both `ClassOne` and `ClassTwo` could implement an interface which provides an access method. This is probably not a good idea in a threaded program. – Meesh Oct 21 '13 at 12:46

1 Answers1

4

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.

noone
  • 19,520
  • 5
  • 61
  • 76
  • Fantastic. First go at generics this morning, and didn't realise that you can extend it with an interface. Makes sense as you've written - I'll test it and upvote/mark etc. when done. Thnx. – James B Oct 21 '13 at 12:50