如何在Java中通过引用调用? [英] How to do call by reference in Java?

查看:196
本文介绍了如何在Java中通过引用调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于Java不支持指针,如何通过Java中的引用来调用函数,就像在C和C ++中一样?

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

推荐答案

Java中不可能实现真正的pass-by-reference。 Java按值传递所有内容,包括引用。但您可以使用容器对象模拟它。

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:


  • 一个数组

  • 一个集合

  • 一个AtomicXYZ类

如果你在一个方法中改变它的内容,改变的内容将可用于调用上下文。

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

哎呀,你显然是指通过引用调用方法。这在Java中也是不可能的,因为方法在Java中不是一级公民。 这可能会在JDK 8中发生变化,但目前,您必须使用接口来解决此限制。

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");
    }
}

使用 Foo 在您的代码中,因此您可以轻松地将 SomeFoo 替换为 OtherFoo

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

这篇关于如何在Java中通过引用调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆