简体   繁体   English

访问Java的私有字段

[英]Accessing private fields of a Java

javax.swing.text.html.ImageView; javax.swing.text.html.ImageView; lines 111 and 258-267 第111和258-267行
http://javasourcecode.org/html/open-source/jdk/jdk-6u23/javax/swing/text/html/ImageView.java.html http://javasourcecode.org/html/open-source/jdk/jdk-6u23/javax/swing/text/html/ImageView.java.html

public class ImageView extends View {
    ....
    private float vAlign;
    ....
}

My program: 我的程序:

.....
ImageView layeredPane = (ImageView) view;
Field privateStringField = layeredPane.getClass().getDeclaredField("vAlign");
privateStringField.setAccessible(true);
layeredPane.vAlign = 2.0;
.....

I get: 我得到:

Test.java:80: error: vAlign has private access in ImageView layeredPane.vAlign = 2.0; Test.java:80:错误:vAlign在ImageView layeredPane.vAlign = 2.0中具有私有访问权限;

How do I fix it? 我如何解决它? I need to put a value of 2.0 我需要将值设为2.0

You fix it by not trying to get at private implementation details. 您可以通过不尝试获取私有实现细节来解决此问题。 Basically you shouldn't be doing this. 基本上,您不应该这样做。 Your code will end up being brittle even when you're still using this version of ImageView , and vulnerable to changes between versions. 即使您仍在使用此版本的ImageView ,您的代码最终也会变得很脆弱,并且容易受到版本之间的更改的影响。 The whole point of it being private is to stop you from accessing it directly. 私有化的全部目的是阻止您直接访问它。

You can fall privateStringField.setFloat(layeredPane, 2.0f) but I would strongly advise against it. 可以使用 privateStringField.setFloat(layeredPane, 2.0f)但我强烈建议您这样做。

(It's odd to call it privateStringField when it's a float field, by the way...) (顺便说一句,当它是一个浮点数字段时,将其称为privateStringField很奇怪...)

First off, why would you want to use 2.0? 首先,您为什么要使用2.0? I thought that the vAlign uses the java.awt.Component contants for BOTTOM_ALIGNMENT, CENTER_ALIGNMENT AND TOP_ALIGNMENT which hold 1.0f, 0.5f, and 0.0f respectively, and so a value of 2.0 may not make much sense. 我认为vAlign使用BOTTOM_ALIGNMENT,CENTER_ALIGNMENT和TOP_ALIGNMENT的java.awt.Component竞争者,它们分别持有1.0f,0.5f和0.0f,因此2.0的值可能没有多大意义。

Regardless, since it's a private field, don't fiddle with it directly and change it via appropriate means. 无论如何,由于它是一个私有领域,所以不要直接摆弄它,而要通过适当的方式对其进行更改。 It appears that this private field is set via attributes: 似乎此私有字段是通过属性设置的:

Object alignment = attr.getAttribute(HTML.Attribute.ALIGN);

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM