Java 获取不使用实例变量的字段的(对象obj)
我不明白为什么get(objectobj)不能处理实例变量(实例字段),并抛出一个IllegalArgumentException 我有以下课程:Java 获取不使用实例变量的字段的(对象obj),java,class,reflection,object,illegalargumentexception,Java,Class,Reflection,Object,Illegalargumentexception,我不明白为什么get(objectobj)不能处理实例变量(实例字段),并抛出一个IllegalArgumentException 我有以下课程: public class InfoSender { String testInt = "hey"; /** * @param args the command line arguments */ public static void main(String[] args) { InfoSender test = new InfoSen
public class InfoSender {
String testInt = "hey";
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
InfoSender test = new InfoSender();
test.asd();
// script g = new script();
// mobile h = new mobile();
}
private void asd() {
new StatusGUI(this);
}
public class StatusGUI extends javax.swing.JFrame {
Class clazz;
/** Creates new form StatusGUI */
public StatusGUI(Object invokerObject) {
initComponents();
setVisible(true);
setLocationRelativeTo(null);
clazz = invokerObject.getClass();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Field[] fields = clazz.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
jTextArea1.append(fields[i].getName() + " | " + fields[i].getType() + " | " + fields[i].get(clazz));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
我有StatusGUI类(不包括initComponents):
public class InfoSender {
String testInt = "hey";
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
InfoSender test = new InfoSender();
test.asd();
// script g = new script();
// mobile h = new mobile();
}
private void asd() {
new StatusGUI(this);
}
public class StatusGUI extends javax.swing.JFrame {
Class clazz;
/** Creates new form StatusGUI */
public StatusGUI(Object invokerObject) {
initComponents();
setVisible(true);
setLocationRelativeTo(null);
clazz = invokerObject.getClass();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Field[] fields = clazz.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
jTextArea1.append(fields[i].getName() + " | " + fields[i].getType() + " | " + fields[i].get(clazz));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
感谢您的帮助:)
Mike。该方法从实际对象中提取值,而不是从类中提取值。应该如此
fields[i].get(invokerObject)
因此,应将invokeObject
设置为StatusGUI
中的一个字段,以便将其传递给jButton1ActionPerformed
方法。简而言之,问题是您使用了错误的方法。你是说:
fields[i].get(clazz)
…其中,clazz
是您试图从中获取字段值的对象的类。这就是为什么您只能看到静态字段。您要做的是这样的:
fields[i].get(invokerObject)
要获取每个实例属性的值,需要传递要从中提取值的对象的实例,而不是对象类的实例
请注意,在调用字段[i].get()之前,您还可以通过调用字段[i].setAccessible(true)
来获取private
和protected
字段的值