开发者

Creating generic method names in generic class?

开发者 https://www.devze.com 2023-02-09 16:11 出处:网络
Currently, I have something like this:- public class MyHolder<T> { private Tvalue; public MyHolder(T t) {

Currently, I have something like this:-

public class MyHolder<T> {
    private T   value;

    public MyHolder(T t) {
        this.value = t;
    }

    public T getValue() {
        return first;
    }

    public void setValue(T t) {
        this.first = t;
    }
}

With this, I can use it like this:-

MyBean bean = new MyBean();
MyHolder<MyBean> obj = new MyHolder<MyBean>(bean);
obj.getVal开发者_StackOverflow中文版ue(); // returns bean

Instead of calling the getter/setter to be getValue() and setValue(..), is it possible to "generify" that too?

Essentially, it would be nice to have it getMyBean() and setMyBean(..), depending on the type passed in. Granted this is a very simple example, however if I create a generic holder class that takes N generic properties, then it would be nice to call it something meaningful instead of getValue1() or getValue2(), and so on.

Thanks.


No. There is no such feature in Java. I can't even imagine how it would look syntactically... void set<T>();? And how would the getter / setter for for instance MyHolder<? extends Number> look?


No, it's not possible unless you use some kind of source code generator to have the MyHolder class generated based on your input.

But on the other hand, even if you had this possibility, how it would be different from using a Map<String, T>? So the invocation would read:

MyBean bean = new MyBean();
MyHolder<MyBean> obj = new MyHolder<MyBean>(bean);
obj.get('value');


No, not possible. Java generics are based on type erasure, i.e. it's mostly syntactic sugar provided by the compiler. That means each generic class is actually implemented by a "raw type" where are type parameters are Object and which already contains all the methods. So it's fundamentally not possible to have different methods depending on type parameters.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号