java:从另一个类获取私有变量,而无需设置getter [英] java: get private variable from another class, without setting a getter

查看:194
本文介绍了java:从另一个类获取私有变量,而无需设置getter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不允许更改类A,但是我需要获取'a'的值(在构造函数中设置).谁能告诉我该怎么做?其他所有解决方案似乎都建议在A类中使用一种吸气剂.我不允许以任何方式对A类进行更改,不得对公众进行更改,等等.魔术必须在B类中发生.

I am not allowed to alter class A, but i need to get the value of 'a'(set in the constructor). Can anyone tell me how to do that? Every other solution seems to propose a getter in class A. I am not allowed to make changes to class A in any way, no changing to public etc. The magic has to happen in class B.

public class A{
    private int a;
    public A(int x){
        a = x * 10;
    }
}

public class B{
    public B(int x){
        A instA = new A(x);
    }

    public int geta(){
        ???
    } 
}

PS:张贴了这个问题,因为每个类似的问题都通过更改A类来回答,而我却不允许这样做.但是由于似乎只有反思,所以可以解决这个问题.谢谢伙计们.

PS: Posted this question, because every similar question was answered with altering class A, whereas i am not allowed to do so. But since there seems to be only reflection, this question can be closed. Thanks guys and gals.

推荐答案

这是 private 字段的全部要点;在封闭类的范围之外无法访问它们.

That is the whole point of private fields; they are not accessible outside the scope of the enclosing class.

您有以下选择:

  1. 更改该类以提供一个吸气剂
  2. 更改总体设计,以使其不需要该值;或寻找另一种方法使这两个类都可以使用
  3. 不推荐:使用反射及其在运行时覆盖私有"保护的功能

这篇关于java:从另一个类获取私有变量,而无需设置getter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆