【问题标题】:Passing a class constant in param在参数中传递一个类常量
【发布时间】:2013-04-18 07:48:52
【问题描述】:

我在java中有一个很小的问题。我想我还没有真正清醒。

我有两个班级:

第一个使用 jar 中的常量(例如:Highgui.CV_LOAD_IMAGE_COLOR)。在第二个中,用户在列表中选择他想要使用的常量。

所以,第二个类调用第一个类的方法,并在参数中使用“stringify”常量。

但是第一个不能使用param中的字符串有一个真正的类常量。

我知道,这是一个非常愚蠢的问题,我很确定我错过了一些明显的东西。

有人有办法解决这个问题吗?

编辑:

一段代码更清楚:

二类

Class1.finder("c:aaa.jpg","Highgui.CV_LOAD_IMAGE_COLOR");

在第一类

public void finder(String path1, String constant){
    Mat object = Highgui.imread(path1, Highgui.CV_LOAD_IMAGE_COLOR);
    //I want to use "constant" instead of Highgui.CV_LOAD_IMAGE_COLOR
}

【问题讨论】:

  • ...teh second class call a method of the first one, with the "stringify" constant to use in param.... 我不知道你是什么意思。您可以发布示例方法调用吗?
  • 我已经用它编辑了我的帖子:)

标签: java string constants param


【解决方案1】:

这看起来像是一个设计问题。传递包含 Java 常量名称的字符串不是一个好主意。为什么不简单地创建一个包含颜色值及其描述的类或枚举:

public enum DescribedColor {
    CV_LOAD_IMAGE_COLOR("CV load image color", "red"),
    ...

    private String description;
    private String color;

    private DescribedColor(String description, String color) {
        this.description = description;
        this.color = color;
    }
}

然后在 Class1 中:

public void finder(String path1, DescribedColor describedColor) {
    ...
}

在 Class2 中:

Class1.finder("c:aaa.jpg", DescribedColor.CV_LOAD_IMAGE_COLOR);

而在显示给用户的列表中,只需要存储所有DescribedColor实例,并将它们的描述作为显示给用户的值。

这样,您就实现了 OO、类型安全、自记录,并且不需要讨厌的反射技巧。

【讨论】:

  • 正是我所需要的 :) 非常感谢......对于这个菜鸟问题很抱歉^^'
猜你喜欢
  • 1970-01-01
  • 2017-07-12
  • 1970-01-01
  • 2021-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多