Java中是否存在指向成员的指针?

时间:2011-07-04 03:47:29

标签: java

我有一个类,它为GUI保留了一些颜色,程序可以根据自己的喜好进行更改。对于GUI的特定元素,我希望能够指定一个颜色,该颜色是该类的成员。在C ++中,我可以使用像

这样的东西
int Pallete::*color = &Pallete::highlight;
Pallete pallete; // made in or passed to the constructor
// ...
void draw() {
    drawing.color(pallete.*color);
    // ...
}

java中是否有等价物?我曾考虑在Class类中使用getField(String),或者使用字符串键保持Map中的颜色,但这些都不是非常好的解决方案,因为它们依赖于字符串,并且编译器无法强制执行他们实际上是Pallete的成员。我还可以将所有颜色名称放在枚举中,并使用一些返回相关颜色的getter函数,但这对我来说似乎更有用。

3 个答案:

答案 0 :(得分:0)

没有直接的等价物,没有。但是你可以声明一个方法

public class Pallette {
    public Color color() {
       return Pallette.highlight;
    }
}

或者显然你可以内联使用highlight

如果highlight不会改变,那么没有什么可以阻止你将它分配给并行常量:

 public static final Color color = Pallette.highlight;

答案 1 :(得分:0)

您可以使用Integer课程。由于它是一个类,它遵循引用语义。

这会给你一个像

这样的课程
class Palette
{
    public static Integer highlight; // this gets initialize to whatever value

    public Integer color = highlight;

}

修改

好的,Integer类描述了一个不可变类型,因此您无法更改Integer所持有的值。不过,解决方案非常简单。您可以定义自己的可变类,如下所示:

class MyInteger {

    private int value;

    public MyInteger(int value) {
        this.value = value;
    }

    public int getValue() {
        return i;
    }

    public void setValue(int value) {
        this.value = value;
    }
}

当然,此示例仅提供最基本的功能。如果您愿意,可以随时添加更多。您可能还发现使用内部Integer而不是int很有用,或者也可能扩展Number类(如Integer类所做的那样)。

如果您声明highlightcolor属于MyInteger类型,并将highlight分配给color,则更改为highlight < em>将反映在color

Palette.highlight.setValue(0);
palette.color = Palette.highlight;
Palette.highlight.setValue(1);
System.out.println(palette.color); // This line will now print "1" instead of "2"

此方法的一个潜在缺点是您无法编写像

这样的作业
Palette.highlight = 0;

相反,您必须使用setValue()来更改MyInteger实例的值。但是,我不认为这是一个很大的损失,因为它实现了您所要求的功能。

答案 2 :(得分:0)

我可能会遗漏一些东西,但这似乎是Java枚举的完美应用。

public enum Pallete
{
    highlight, normal, redact
};

Pallete color = Pallete.highlight;
void draw() {
    drawing.color(color);
}

您可能希望我的“Pallete”成为您的Pallete类的成员,而不是独立的枚举 - 无论哪种方式都可以。

Enum比这更强大。例如,您可以添加功能以提供颜色的RGB值。

相关问题