A strongly referenced class in Java, used for anonymous classes

I want to use hard reference classes in my java code, but, of course, none Is there any other way to do what I want, or should I have my own class?

This will provide an anonymous class in the method. I want the anonymous class to set the return value of the method

For example, given

interface Greeting {
    void greet();
}

I want the following code:

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

I can fake it with a list:

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

But I don't want to use lists I can write a strongreference class to solve this problem:

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

This makes my approach clearer:

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

For my design example, I can have greet () return a string, but I'm working with more complex classes where settings go deep into database calls managed by the base class Instances have many different types they want to return, so I've been using the list technique

My question is: is there a better way? What's wrong with my strongreference class? Has anyone written strongreference in a library?

Solution

If you want something with a standard API, maybe atomicreference will?

It has void set (V value) and V get () methods Unless you involve multiple threads, you only need to treat the synchronization mechanism as a reward; -)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>