加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java中强引用的类,用于匿名类

发布时间:2020-12-15 04:55:40 所属栏目:Java 来源:网络整理
导读:我想在我的 Java代码中使用硬引用类,但是,当然,没有一个.有没有其他方法可以做我想要的,或者我应该自己上课? 这会在方法中提供匿名类,我希望匿名类设置方法的返回值. 例如,给定 interface Greeting { void greet();} 我想要以下代码: // Does not compiles
我想在我的 Java代码中使用硬引用类,但是,当然,没有一个.有没有其他方法可以做我想要的,或者我应该自己上课?

这会在方法中提供匿名类,我希望匿名类设置方法的返回值.

例如,给定

interface Greeting {
    void greet();
}

我想要以下代码:

// Does not compile
static void hello(final String who) {
    String returnValue;

    Greeting hello = new Greeting() {
        public void greet() {
            returnValue = "hello" + who;
        }
    };
    hello.greet();
    System.out.println(returnValue);
}

我可以使用列表伪造它:

static void hello(final String who) {
    final List<String> returnValue = new ArrayList<String>();
    Greeting hello = new Greeting() {
        public void greet() {
            returnValue.add("hello" + who);
        }
    };

    hello.greet();
    System.out.println(returnValue.iterator().next());
}

但我不想使用列表.我可以写一个StrongReference类来解决这个问题:

static class StrongReference<T> {
    private T referent;
    public void set(T referent) {
        this.referent = referent;
    }
    public T get() {
        return referent;
    }
}

这使我的方法更清晰:

static void hello(final String who) {
    final StrongReference<String> returnValue = new StrongReference<String>();
    Greeting hello = new Greeting() {
        public void greet() {
            returnValue.set("hello" + who);
        }
    };

    hello.greet();
    System.out.println(returnValue.get());
}

对于我的设计示例,我可以让greet()返回一个String,但我正在处理更复杂的类,其中的设置深入基类管理的数据库调用.实例有许多他们想要返回的不同类型,所以我一直在使用List技巧.

我的问题是:有更好的方法吗?我的StrongReference课有什么问题?有没有人在某个库中写过StrongReference?

解决方法

如果你想要标准API的东西,也许 AtomicReference会这么做?

它有void set(V值)和V get()方法.除非您涉及多个线程,否则只需将同步机制视为奖励;-)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读