我正在尝试致电String.format()
String
和Object[]
。我该怎么办?
答案 0 :(得分:14)
就是这样:
String.format(myString, myArray);
答案 1 :(得分:12)
您应该可以致电
String text = String.format(formatString, args);
...假设您希望args
为多个值。如果你需要额外的包装,你必须自己做:
String text = String.format(formatString, new Object[] { args });
基本上,如果参数类型已经与参数数组类型匹配,则编译器不会进行任何包装。
来自JLS,15.12.4.2部分:
如果使用kn实际参数表达式调用m,或者,如果使用k = n实际参数表达式调用m并且第k个参数表达式的类型与T []不匹配,则参数列表( e1,...,en-1,en,... ek)被评估为好像它被写为(e1,...,en-1,new T [] {en,...,ek})
注意开头的“如果” - 这就是有效地说,如果参数已经合适,则不会执行换行。
答案 2 :(得分:6)
简而言之:
( S2 和 I2 可能是最有趣的版本传递 varargs为Object[]
)
PrintStream ps = System.out ;
String[] sarr = new String[] { "a" , "b" } ;
Object os = sarr ;
int[] iarr = new int[] { 1 , 2 } ; // cannot be cast to Object[] - see I6 below
Integer[] ioarr = new Integer[] { 1 , 2 } ; // can be cast to Object[] - see I2 below
Object oi = iarr ; // cannot be cast to Object[] - see I6 below
ps.printf( "%n## Strings:%n%n" ) ;
ps.printf( "S1: pass as single objects: %s, %s%n" , "a" , "b" ) ;
ps.printf( "S2: pass as varargs objects: %s, %s%n" , (Object[]) sarr ) ;
ps.printf( "S3: pass as single objects: %s, %s%n" , sarr , "c" ) ;
ps.printf( "S4: pass as single objects: %s, %s%n" , os , "c" ) ;
// ps.printf( "S5: MissingFormatArgumentException: %s, %s%n" , os ) ;
// ps.printf( "S6: ClassCastException: %s, %s%n" , (Object[]) os ) ;
ps.printf( "%n## int:%n%n" ) ;
ps.printf( "I1: pass as single objects: %s, %s%n" , 1 , 2 ) ;
ps.printf( "I2: pass as varargs objects: %s, %s%n" , (Object[]) ioarr ) ;
ps.printf( "I3: pass as single objects: %s, %s%n" , iarr , 3 ) ;
ps.printf( "I4: pass as single objects: %s, %s%n" , oi , 3 ) ;
// ps.printf( "I5: MissingFormatArgumentException %s, %s%n" , iarr ) ;
// ps.printf( "I6: ClassCastException: %s, %s%n" , (Object[]) oi ) ;
输出:
## Strings:
S1: pass as single objects: a, b
S2: pass as varargs objects: a, b
S3: pass as single objects: [Ljava.lang.String;@ad02649, c
S4: pass as single objects: [Ljava.lang.String;@ad02649, c
## int:
I1: pass as single objects: 1, 2
I2: pass as varargs objects: 1, 2
I3: pass as single objects: [I@6781882a, 3
I4: pass as single objects: [I@6781882a, 3