Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to create "anonymous" class on the fly

I can do this:

new Object(){
    public void hi(){}
}.hi();

how do i (or can i) do this:

IWouldRatherStayAnonymous t = new IWouldRatherStayAnonymous extends Thread(){
    public void NoNoYouCantCallMe(String s){}
};
t.NoNoYouCantCallMe("some useful data that i will need later, but don't want to save this anonymous class");

and if i can't syntactically do this, can anyone explain the logic/implementation design that of why this would never work?

==========================================

Edit: clarifications - I would like to create an anonymous class without saving it, and then instantiate an instance of that anonymous class. I only need 1 reference, since i don't plan on using this reference often (nor do i want anything else even in the same outer class to use it). However, I would like simply like to pass some data to this anonymous class only once (ideally the constructor, but you will notice that you can't actually override the constructor in Thread()).

It's really not a HUGE deal, I was just curious if this was doable, but it seems from some of the answers that it is feasible, but just not very pretty.

like image 377
David T. Avatar asked Sep 02 '26 20:09

David T.


1 Answers

Your question is a little confusing, but it sounds like you want a class that both extends Thread and implements some interface, but which can't be accessible outside of the method it's being used by (which would rule out even private nested classes). In that case use a local class:

void myMethod() {
    class Impl extends Thread implements SomeInterface {
        @Override
        public void someInterfaceMethod(String s){ }
    }
    new Impl().someInterfaceMethod("data");
}

EDIT: In response to your update, you can naturally give the local class a constructor and pass in data, or just let it close over final variables in the outer method.

like image 91
Paul Bellora Avatar answered Sep 05 '26 10:09

Paul Bellora



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!