我正在开发一个 open source API用于轻松测量自定义对象的运行时分配。虽然我可以很好地编写缓存处理算法,但在有机地访问自定义对象中的所有数据类型时遇到问题。我想编写此 API 来获取任何自定义对象,只要它当前支持以下数据类型即可:
- 整数
- 字符串
- 简短
- 字节
- 长
- float
- 双
- 查尔
- boolean 值
- 位图(仅适用于 Android,但可以排除)
例如,采用这个自定义对象类
package productions.widowmaker110.byteme;
/**
* Created by Widowmaker110 on 11/20/2015.
*
* This object class is meant to mimick possible data types held within a single object
*
* For simplicity, I will be mimicking a simplified user profile data
*/
public class ExampleObject {
private String Name;
private int Age;
private String Location;
private String Sex;
private String Description;
/**
* Empty Constructor
*/
public ExampleObject() {}
/**
* Basic constructor with initializing data
*
* @param _Name String with the name of the user
* @param _Age Integer with the age of the user
* @param _Location String containing the curret city and state of the user
* @param _Sex String Male, Female, Transgender, or Other
* @param _Description String short blurb about the user
*/
public ExampleObject(String _Name, int _Age, String _Location, String _Sex, String _Description)
{
this.setName(_Name);
this.setAge(_Age);
this.setLocation(_Location);
this.setSex(_Sex);
this.setDescription(_Description);
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
public String getLocation() {
return Location;
}
public void setLocation(String location) {
Location = location;
}
public String getSex() {
return Sex;
}
public void setSex(String sex) {
Sex = sex;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
}
我想要做的就是采用类似的方法,并将所有数据点“传输”到我的缓存处理类,同时如果我可以帮助它,则将对象保持在当前形式。我的第一个想法是让一个对象拥有给定对象的每种数据类型的数组,但对我来说以这种方式解构自定义对象似乎很复杂。我可能看错了,但如果我这样做:
Object(int[] int_array, String[] string_array, short[] short_array,
long[] long_array, byte[] byte_array, float[] float_array,
double[] double_array, char[] char_array, boolean[] boolean_array,
Bitmap[] bitmap_array)
并要求程序员将所有数据点放入数组中。
我对该 API 的最终目标是将其放入项目中,并立即为您完成所有讨厌的缓存处理。
编辑 我很抱歉说得不清楚。我试图给出该项目的整个范围,但可能给出的太多了。有没有什么方法可以获取自定义类并解析它,而无需知道哪些字段可用,只要它们落入我在顶部制作的项目符号列表中即可?我可以自己做缓存部分。这样是不是更清楚了?
编辑 #2 JFPicard 指出使用 Java 反射进行此类处理。看完oracle documentation还有这些:
我发现这样的东西非常有帮助。
import java.lang.reflect.Method;
...
Method[] methods = MyObject.class.getMethods();
for(Method method : methods){
System.out.println("method = " + method.getName());
}
谢谢!
最佳答案
我认为你需要使用反射来获取对象的所有 getter 并获取数据来执行某些操作。
这里有一个很好的教程可以帮助您:https://docs.oracle.com/javase/tutorial/reflect/member/methodModifiers.html
关于java - 有什么方法可以获取自定义对象中的所有数据类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33835788/