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 }
Solution 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>
.
publicclassParseMyData<TextendsDataProvider> {
T classOneOrClassTwo;
ParseMyData(T t) {
classOneOrClassTwo = t;
}
publicvoidparseIt() {
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.
Post a Comment for "Accessing Field Variable From Generic Object"