Inline class that extends a type parameter

I want to write a quick and dirty helper class that can quickly save my objects. Therefore, I use OrmLite.

I don't want to add annotations to my classes, so I'm trying to add a shell on the fly without any bytecode libraries.

<T> void save(T o) {
    @DatabaseTable
    class wrap extends T {
        @DatabaseField(generatedId = true)
        public Long id;
    }

    try {
        Dao<T, Long> d = (Dao<T, Long>) getClassDao(o.getClass());
        TableUtils.createTableIfNotExists(connectionSource, o.getClass());
        d.createOrUpdate(o);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

The problem class wrap extends Tis why it is impossible to expand T?

+4
source share
3 answers

This is a strange but interesting question! It is difficult to give an accurate and comprehensive answer. There are probably many different reasons, but I think the following is the most important:

save. class wrap extends T T save , , . save , save T - , . ( , , . .)

- . Java - , . , Java ( , , ++). , , , , .

+3

<T> - , . - , , - -. <T>, ,

+2

Because T can be final. Final classes cannot be extended.

At least, this is a logical reason prohibiting the distribution of the generic type. Technical experience is explained in other answers.

+1
source

Source: https://habr.com/ru/post/1652585/


All Articles