java 引用调用,如何在Java中通过引用调用?

由于Java不支持指针,直接的引用调用函数是不可能的。Java通过值传递一切,包括引用。但可以通过容器对象如数组、集合或Atomic类来模拟。在方法中改变这些容器的内容,在调用上下文中也是可见的。另外,Java中不能直接通过引用调用方法,这可能在JDK8中有所改变,目前通常使用接口来规避这一限制。
摘要由CSDN通过智能技术生成

Since Java doesnt support pointers, How is it possible to call a function by reference in Java like we do in C and C++??

解决方案

Real pass-by-reference is impossible in Java. Java passes everything by value, including references. But you can simulate it with container Objects.

Use any of these as a method parameter:

an array

a Collection

an AtomicXYZ class

And if you change its contents in a method, the changed contents will be available to the calling context.

Oops, you apparently mean calling a method by reference. This is also not possible in Java, as methods are no first-level citizens in Java. This may change in JDK 8, but for the time being, you will have to use interfaces to work around this limitation.

public interface Foo{

void doSomeThing();

}

public class SomeFoo implements Foo{

public void doSomeThing(){

System.out.println("foo");

}

}

public class OtherFoo implements Foo{

public void doSomeThing(){

System.out.println("bar");

}

}

Use Foo in your code, so you can easily substitute SomeFoo with OtherFoo.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值