0

I want to write a function that, given an arbitrary java bean as an argument, returns an object that is a copy of that bean but that belongs to an anonymous subclass of the bean's type that contains an additional property. Let me illustrate with an example of what I have so far:

Foo.java:

import lombok.Data;
import lombol.AllArgsConstructor;

@Data
@AllArgsConstructor
public class Foo {
    private String bar;
    private String baz;
}

Garply.java:

public class Garply {
    Foo fooWithQux(Foo foo, String quxVal) {
        return new Foo(foo.bar, foo.baz) {
            private String qux;

            public String getQux() {
                return quxVal;
            }
        };
    }
}

This seems silly because I can never actually call getQux(), but a tool I work with uses reflection to successfully find the qux property and do what I want with it.

My issue is that I don't want to have separate fooWithQux() functions for each type that I want to be able to add the qux property to. Ideally I'd have something like beanWithQux() that accepts objects of arbitrary type. I think I could make this work with something like the following:

public T beanWithQux<T>(T bean, String quxVal) {
    class BeanWithQux extends T {
        private String qux;

        BeanWithQux(T bean, String quxVal) {
            // Here's where I'd like to copy all of the properties
            // from the Bean into the BeanWithQux

            qux = quxVal;
        }

        public getQux() {
            return qux;
        }
    }

    return BeanWithQux(bean, quxVal);
}

Here's where I'm stuck. I don't know to copy all of the properties from the given object into my new object. Anyone have ideas? Ideally there would be something I could do using lombok (I control the Foo class and can add annotations like @Builder if need be) as opposed to writing a bunch of reflection magic myself.

Thanks!

1 Answer 1

1

I think in this case using runtime bytecode weaving is a better approach, since you don't need to call the methods in your own codebase.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.