我可以在Java的泛型函数中为泛型对象的特定属性设置值吗?

huangapple go评论99阅读模式
英文:

Can I set value for specific property of generic object in generic function in java?

问题

我有一个负责保存通用对象的函数,如下所示:

public <T> T save(final T o){
    return (T) getCurrentSession().save(o);
}

我的对象具有一些常见的特定属性,比如createDate、createId、updateId、updateDate等等。我是否可以在我的保存函数中设置这些属性,就像这样:

o.setProperty("propertyName", value)
英文:

I have a function which is responsible to save generic object like that:

public &lt;T&gt; T save(final T o){
        return (T) getCurrentSession().save(o);
    }

My object have some common specific properties such as createDate, createId, updateId, updateDate,...
Can I set these properties in my save function like:

o.setProperty(&quot;propertyName&quot;, value)

答案1

得分: 4

你可以对类型参数 T 设置界限,以使你能够从你定义的接口中调用它的方法:

    interface MyObject {
        void createDate();
        void createId();
        ...
    }
    public <T extends MyObject> T save(final T o){
        o.createDate();
        return (T) getCurrentSession().save(o);
    }
英文:

You can put bounds on the type parameter T to allow you to call methods on it from an interface you have defined:

    interface MyObject {
        void createDate();
        void createId();
        ...
    }
    public &lt;T extends MyObject&gt; T save(final T o){
        o.createDate();
        return (T) getCurrentSession().save(o);
    }

答案2

得分: 0

你可以使用Java的反射(Reflection)API来创建一个通用的设置器(setter)。
虽然有点不太优雅,直接了当,不具备类型安全性,且涉及过多的Object值,但仍然是一个可行的解决方案。

public Object setValue(Object classObject, String fieldIdentifier, Object value) {
    Class<?> clazz = classObject.getClass();
    Field retrievedField = Arrays.stream(clazz.getDeclaredFields())
        .filter(field -> field.getName().equalsIgnoreCase(fieldIdentifier))
        .findFirst().orElse(null); // 在这里添加一个当null时的异常处理

    retrievedField.setAccessible(true);
    retrievedField.set(classObject, value);
    return classObject;
}
英文:

You can use Java Reflection API to create an universal setter.
A bit ugly, straightforward, not typesafe and too many Object values but still a working solution.

public Object setValue(Object classObject, String fieldIdentifier, Object value) {
    Class&lt;?&gt; clazz = classObject.getClass();
    Field retrievedField = Arrays.stream(clazz.getDeclaredFields()) 
  .filter(field -&gt; field.getName().equalsIgnoreCase(fieldIdentifier))
            .findFirst().orElse(null);//add an exception here when null

    retrievedField.setAccessible(true);
    retrievedField.set(classObject, value);
    return classObject;
}

huangapple
  • 本文由 发表于 2020年10月26日 08:51:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/64530299.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定