[英]Passing a class constant in param
I've a very little problem in java. 我在Java中有一个小问题。 I think i'm not still really awake.
我想我还没有真正醒着。
I have two classes: 我有两节课:
The first one use constants from a jar (example : Highgui.CV_LOAD_IMAGE_COLOR). 第一个使用jar中的常量(例如:Highgui.CV_LOAD_IMAGE_COLOR)。 In the second one the user select in a list which constant he want to use.
在第二个中,用户在列表中选择他要使用的常数。
So, the second class call a method of the first one, with the "stringify" constant to use in param. 因此,第二个类调用第一个方法,并在参数中使用“ stringify”常量。
But the first one can't use the string in param has a real class constant. 但是第一个不能在param中使用字符串的对象具有真实的类常量。
I know, that's a really stupid problem, I'm pretty sure I'm missing something obvious. 我知道,这是一个非常愚蠢的问题,我很确定自己缺少明显的东西。
Someone have an idea to deal with that? 有人有想法应对吗?
Edit : 编辑:
A piece of code for more clarity : 一段代码更加清晰:
In Class2 在Class2
Class1.finder("c:aaa.jpg","Highgui.CV_LOAD_IMAGE_COLOR");
In Class1 在Class1中
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
}
This looks like a design problem. 这看起来像一个设计问题。 Passing strings around, containing the name of a Java constant, is not a good idea.
传递包含Java常量名称的字符串不是一个好主意。 Why don't you simply create a class, or an enum, containing the value of your color and its description:
为什么不简单地创建一个包含颜色值及其描述的类或枚举:
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;
}
}
Then in Class1 : 然后在Class1中:
public void finder(String path1, DescribedColor describedColor) {
...
}
And in Class2 : 在Class2中:
Class1.finder("c:aaa.jpg", DescribedColor.CV_LOAD_IMAGE_COLOR);
And in the list displayed to the user, you just need to store all the DescribedColor instances, and use their description as the value displayed to the user. 在显示给用户的列表中,您只需要存储所有DescribedColor实例,并将其描述用作显示给用户的值即可。
This way, you're OO, type-safe, self-documenting, and don't need nasty reflection tricks. 这样,您就可以了,是面向对象的,类型安全的,具有自说明性,并且不需要讨厌的反射技巧。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.