简体   繁体   English

当class1对象通过反射在另一个class2中私有声明时,如何访问class1的私有变量的值?

[英]How to access a value of a private variable of a class1 when the class1 object is privately declared in another class2 via reflection?

I am trying to access private field of department after passing course as an object to function. 我试图通过课程作为一个对象来访问部门的私人领域。 Department is a private variable in course. 部门当然是一个私人变量。 The solution needs to be generic as this is a reflection exercise. 解决方案需要是通用的,因为这是一个反思练习。 At run time the store object function doesn't know which type of object is being passed so i cant use type casting either. 在运行时,存储对象函数不知道传递了哪种类型的对象,因此我也不能使用类型转换。 this is department class: 这是部门类:

public class Department{
  private String departmentName;
  private Teacher departmentHOD;
}

this is Course class: 这是课程课程:

public class Course {
  private String courseNumber;
  private String semesterName;
  private String courseName;
  private Department offeringDepartment;
  private Teacher[] courseInstructors;
  private int sectionNumbers;
}

in main I pass course in a function void storeObject(Object o): 在main中我在函数void storeObject(Object o)中传递过程:

void storeObject(Object o)
{
 //in this function i need to extract all possible primitive datatype objects and save them in a data base
Class classForStorage = o.getClass();
Field[] publicFields = classForStorage.getDeclaredFields();//.getFields()
    for (int i = 0; i < publicFields.length; i++) 
    {   //  making private ones accessible
        publicFields[i].setAccessible(true);
        //Getting name and type of all attributes in the class one by one
        String fieldName = publicFields[i].getName();
        Class typeClass = publicFields[i].getType();
        String fieldType = typeClass.getName();
       ......//after this i access values by datatype and store in sql
       //but it only works for primitive data types
    }

I cant access departname using something like: 我不能使用以下内容访问departname:

  publicFields[i].getType().getDeclaredFields()[0].setAccessible(true);
  value =(String)publicFields[i].getType().getDeclaredFields()[0].get(obj); 

this gives me illegal access exception 这给了我非法访问异常

On a side note how can get values from the courseInstructor array. 另外,请注意如何从courseInstructor数组中获取值。

Edit: "via reflection" was added to the question header after this answer was posted. 编辑:发布此答案后,“通过反射”已添加到问题标题中。 If the solution must be using reflection, this answer is not applicable. 如果解决方案必须使用反射,则此答案不适用。

The generic solution you seek is : 您寻求的通用解决方案是:

 public class Course {
   private String courseNumber;
   private String semesterName;
   private String courseName;
   private Department offeringDepartment;
   private Teacher[] courseInstructors;
   private int sectionNumbers;

   //add a getter to Course 
   public Department getDepartment() {
     return offeringDepartment
   }
}

To retrieve department use 检索部门使用

Course course = new Course();
Department department = course.getDepartment();

If 'o' object is an instance of 'Course' you can: 如果'o'对象是'课程'的实例,您可以:

//cast object to Course and use getter 
((Course)o).getDepartment();

You're overthinking this. 你是在思考这个问题。

void printObject( Object o ) {
    for ( Field fld : o.getClass().getDeclaredFields() ) {
        fld.setAccessible( true );
        System.out.println( fld.get( o ) );
    }
}

If you need your method to behave differently if the field is an array, use isArray . 如果字段是数组,如果需要方法的行为不同,请使用isArray

void printObject( Object o ) {
    for ( Field fld : o.getClass().getDeclaredFields() ) {
        fld.setAccessible( true );
        Object oFldVal = fld.get( o );
        if ( fld.getType().isArray() ) {
            int iLen = Arrays.getLength( oFldVal );
            for ( int i = 0; i < iLen; ++i ) {
                printObject( Arrays.get( oFldVal, i ) );
            }
        } else {
            System.println( oFldVal );
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用反射找到Class2中引用Class1的位置? - How to find where Class1 is referenced in Class2 using reflection? 如何将classText从class1设置为class2? - How to setText from class1 to class2? 在扩展Class1的Class2中使用Class1的方法值 - use method value of Class1 in Class2 which extends Class1 Class1具有ArrayList <Class2> ,但Class2具有单个Class1实例? - Class1 has ArrayList<Class2>, but Class2 has a single Class1 instance? 如何将变量从 class1 的静态函数传递给另一个 class2? - How to pass variables from a static function of class1 to another class2? 如何在另一个类中使用在class1中创建的变量? - How to use a variable created in class1, in another class? 通过从Jframe class3的jtable中选择一个项来更改JFrame class1,JFrame class2等文本化的值 - Changing the value of a textfied in JFrame class1, JFrame class2,… by selecting an item from jtable in Jframe class3 显示使用class2 libgdx中的对象在class1中加载的Texture - Display a Texturethat is loaded in class1 using its object in class2 libgdx JAVA:从Class1获取String值并调用另一个Class2 - JAVA: get String value from Class1 and call to the other Class2 Jackson-将class1的json表示形式的Object type字段映射到class2 - Jackson - Mapping an Object type field of json representation of class1 to class2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM