[英]Accessing Field Variable from Generic Object
I have two classes, ClassOne
and ClassTwo
, that update a public field data
ie, 我有两个类,
ClassOne
和ClassTwo
,它们更新公共字段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
. 在任何给定时间,只有一个类及其相关线程正在运行,即,该应用在运行时检测到数据源并使用
ClassOne
或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
. 我想在一个名为
ParseMyData
的单独类中解析数据,但是对于设置ParseMyData
的最佳方法有些困惑,因此ParseMyData
可以从ClassOne
或ClassTwo
访问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
转换为ClassOne
或ClassTwo
。 But I'd recommend you to go with the first option. 但我建议您选择第一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.