lundi 6 août 2018

Use Class Object as Type

My class hierarchy is as follows:

  • PersistedObject (cannot modify or extend this)
    • Foo
    • Bar
    • Baz

Where Foo, Bar, Baz are classes that extend PersistedObject. However there's a code smell, Foo, Bar and Baz have, each, an implementation of object copying that's basically the same in each class, sans a Type literal:

protected PersistedObject copy() {
    Foo copy = toBuilder().build();
    copy.copyPersistedObject(this);
    return copy;
}

Where I get copyPersistedObject through the superclass, and it implements logic related to database-persistence.

So I want to remove all this boilerplate from Foo, Bar and Baz. Ideally I'd get to this point:

  • PersistedObject (cannot modify or extend this)
    • CustomPersistedObject
      • Foo
      • Bar
      • Baz

That is, I want to make a single implementation of copy() and make it so Foo, Bar and Baz all extend from my CustomPersistedObject class.

The thing, though, is that the first line of that copy() method requires me to use a concrete type to cache the state of the object pre-copy since Foo, Bar and Baz each add their own different fields to PersistedObject, then execute copyPersistedObject() to deal with the database stuff, and finally return the state which I have captured after the copyPersistedObject call.

So, I'm kind of trying to wrap my head around reflection to get this done, is there any way that I can get the .class of a java object in runtime and then use it as a type itself to instantiate?

I want to get to a point like this:

protected PersistedObject copy() {
    Class<?> clazz = this.getClass();
    [clazz.asType] copy = toBuilder().build();
    copy.copyPersistedObject(this);
    return copy;
}





Aucun commentaire:

Enregistrer un commentaire