File tree Expand file tree Collapse file tree
Scala_Java_Override_Variable_Parameter Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ ### Scala重写Java可变参数方法问题 ###
2+
3+ ``` Java
4+ public interface KeyGenerator {
5+ /**
6+ * Generate a key for the given method and its parameters.
7+ * @param target the target instance
8+ * @param method the method being called
9+ * @param params the method parameters (with any var-args expanded)
10+ * @return a generated key
11+ */
12+ Object generate (Object target , Method method , Object ... params );
13+ }
14+ ```
15+
16+ 如以上的Java接口,Java中的可变参数是以...出现,而Scala则不同,Scala的可变参数是以* 出现的,如下:
17+
18+ ``` Scala
19+ def generate (target: Object , method : Method , params : Object * ): Object = {
20+ // 省略
21+ }
22+ ```
23+
24+ 如果你使用IDE自动生成的方法参数如下:
25+
26+ ``` Scala
27+ def generate (target: Any , method : Method , params : Array [AnyRef ]): Object = {
28+ // 省略
29+ }
30+ ```
31+
32+ 在使用Scala重写了KeyGenerator接口的generate方法时编译器总是无法通过,即在Scala中使用params: Object* 或者是Array[ AnyRef] 是无法替代Object... params的,注意Scala中的Any和AnyRef都是Object类型,classOf[ Any] 和classOf[ AnyRef] 都是Object类型,解决办法是你只需要将Array[ AnyRef] 修改成AnyRef* 就可以编译通过了。
33+
34+ ``` Scala
35+ def wiselyKeyGenerator (): KeyGenerator = {
36+ new KeyGenerator () {
37+ override protected def generate (target : Any , method : Method , params : AnyRef * ): Object = {
38+ var sb = new StringBuilder ()
39+ sb.append(target.getClass().getName())
40+ sb.append(method.getName())
41+ for (param <- params) {
42+ sb.append(param.toString())
43+ }
44+ sb.toString()
45+ }
46+ };
47+ }
48+ ```
You can’t perform that action at this time.
0 commit comments