[背景:刚接触Java不到4个月,是C++老手。]
我正在开发一个需要在多处使用固定大小的数组(“固定字符串”)的库。我尝试使用依赖注入(详见q.v.)来解决这个问题,因此我希望得到以下形式的内容:
class Foo
{
private Bar injectedBar;
private char[] injectedFixedString;
Foo(Bar injectedBar, /* what can go here? */ char[5] injectedFixedString);
{ /* initializing code goes here /* }
}
需要简单明了——这将进入一个自动生成的通讯协议。我对协议和数据库没有任何控制权;在最终代码中,我将有数百甚至数千个这样的实例。所以,考虑到所有这些:
我的唯一选择是使用C++吗?
char injectedFixedString[5];
创建一个自定义的类?类似于以下内容:
class FixedBarString {
/* could also set this in the constructor, but this complicates code generation a tad */
public static integer STRING_SIZE = 5; /* string size */
char[] fixedString = new char[STRING_SIZE];
FixedBarString(char[] string) throws RuntimeException {
/* check the string here; throw an exception if it's the wrong size.
I don't like constructors that throw however. */
}
public void setString(char[] string) throws RuntimeException {
/* check the string here */
}
public char[] getString() {
/* this isn't actually safe, aka immutable, without returning clone */
}
public char[] createBlankString() {
return new char[STRING_SIZE];
}
}
感谢您。如果这段代码太多了,我很抱歉。
myMethod(char myarray[5])
。 - dogbanechar array[3]
调用这个方法,编译器会提示你这是不合法的。当你使用静态大小的数组时,编译器能够检测类型不匹配的情况。 - dogbane