How to pass an anonymous class (not an instance) as a parameter to a method that expects a class type in Java

I need to call a method that takes a parameter Class:

public action(Class<? extends SomeInterface> classVariable);

I can do it:

action(new SomeInterface() { 
    // implement interface
  }.getClass());

But can I leave without instantiating the object and calling getClass()?

+3
source share
4 answers

How can you access an anonymous class without an instance? You will need a name to refer to it in some way, which by definition does not have (of course, it will have some name generated by the compiler at run time, but to request that you need to create it first, and you cannot create it without instantiating it).

, .

+5

:

public void action(Class<? extends SomeInterface> classVariable);

:

action(new SomeInterface() { // implement interface }.getClass());

:

interface I {}

class A implements I
{    
}

public void action(Class<? extends I> c)
{
}


public void test()
{
   action(new I() {}.getClass());
}
0

Anonymous classes cannot be safely named by name, but only by instance. You can predict the name and use it, but not too elegantly or reliably.

private void neverCalled() {
    SomeInterface si = new SomeInterface() { 
        // implement interface
    };
}

Class anon = Class.forName(getClass()+"$1"); // hopefully its the first!

It is much easier to give the class a name and use it. Many IDEs make it easy to change from one to another.

0
source

Perhaps you are looking for this?

action(SomeInterface.class);

I think this may be what you are looking for, but it does not include anonymous classes at all.

This can help get more detailed information about what the method does actionwith reference to the class.

0
source

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


All Articles