java中转换方法_在Java中转换为具体类和调用方法

如果方法调用返回有问题的类的实例,则可以通过一些工作来完成此操作,这是您的具体问题(上图)。

import static java.lang.System.out;

public class AATester {

public static void main(String[] args){

for(int x: new int[]{ 0, 1, 2 } ){

A w = getA(x);

Chain.a(w.setA("a")).a(

(w instanceof C ? ((C) w).setC("c") : null );

out.println(w);

}

}

public static getA(int a){//This is whatever AA does.

A retval;//I don't like multiple returns.

switch(a){

case 0: retval = new A(); break;

case 1: retval = new B(); break;

default: retval = new C(); break;

}

return retval;

}

}测试类A

public class A {

private String a;

protected String getA() { return a; }

protected A setA(String a) { this.a=a; return this; }//Fluent method

@Override

public String toString() {

return "A[getA()=" + getA() + "]";

}

}测试B级

public class B {

private String b;

protected String getB() { return b; }

protected B setB(String b) { this.b=b; return this; }//Fluent method

@Override

public String toString() {

return "B[getA()=" + getA() + ", getB()=" + getB() + "]\n "

+ super.toString();

}

}测试类C.

public class C {

private String c;

protected String getC() { return c; }

protected C setC(String c) { this.c=c; return this; }//Fluent method

@Override

public String toString() {

return "C [getA()=" + getA() + ", getB()=" + getB() + ", getC()="

+ getC() + "]\n " + super.toString();

}

}连锁课

/**

* Allows chaining with any class, even one you didn't write and don't have

* access to the source code for, so long as that class is fluent.

* @author Gregory G. Bishop ggb667@gmail.com (C) 11/5/2013 all rights reserved.

*/

public final class Chain {

public static _ a(K value) {//Note that this is static

return new _(value);//So the IDE names aren't nasty

}

}连锁的助手类。

/**

* An instance method cannot override the static method from Chain,

* which is why this class exists (i.e. to suppress IDE warnings,

* and provide fluent usage).

*

* @author Gregory G. Bishop ggb667@gmail.com (C) 11/5/2013 all rights reserved.

*/

final class _ {

public T a;//So we can reference the last value if desired.

protected _(T t) { this.a = T; }//Required by Chain above

public _ a(K value) {

return new _(value);

}

}输出:

A [get(A)=a]

B [get(A)=a, getB()=null]

A [getA()=a]

C [getA()=a, getB()=null, getC()=c)]

B [get(A)=a, getB()=null]

A [get(A)=a]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值