java - Passing the child instance on construction -



java - Passing the child instance on construction -

i have parent class has methods need utilize child's class instance, can't seem pass via constructor:

public abstract class codelanxplugin<e extends codelanxplugin<e>> /* other inheritance */ { private final e plugin; public codelanxplugin(e plugin) { this.plugin = plugin; } @override public void onenable() { //need able utilize plugin instance } }

however, because kid class has able collect kid instance in form before onenable called, came this:

public class myplugin extends codelanxplugin<myplugin> { public myplugin() { super(this); }

which of course of study not possible since can't super(this). how can pass kid instance upon construction?

one thought had was:

public myplugin() { super(new box<myplugin>(this).getinst()); } private class box<e> { private e inst; public box(e inst) { this.inst = inst; } public e getinst() { homecoming this.inst; } }

however still calls this before super() called, it's still illegal.

one reason cannot simple utilize this in parent class in first place pass e type argument other classes:

protected listenermanager<e> listener; @override public void onenable() { //... this.getlogger().log(level.info, "enabling listeners..."); this.listener = new listenermanager<>(/* need e instance */); //... }

if pass this listenermanager constructor, receive compiler error:

error: incompatible types: cannot infer type arguments listenermanager<>

if utilize new listenermanager<e>(this), error is:

error: incompatible types: codelanxplugin cannot converted e

you don't need pass "this" parent's constructor. 'this' within myplugin's constructor refer same object 'this' within codelanxplugin's constructor.

so writing simply:

public codelanxplugin() { this.plugin = (e) this; }

and then, should wonder wy you'd need "plugin" field anyway, since "this" available... explanation, sense looking template method design pattern.

java generics

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -