简体   繁体   中英

Class reference for a Java inner class

Is there a way to refer to any inner class?

I would like to specify a return type compatible with an inner class eg

Class<OuterClass.*> some_method();

I understand this syntax is invalid. Is there a way to express this?

I know I can't use something like Class<? extends OuterClass> Class<? extends OuterClass> because an inner class doesn't extend an outer class.

Well, you can refer to specific inner classes, at least:

<T extends OuterClass.InnerClass> Class<T> some_method()

Besides that, what would you gain by returning an object of any inner class? That would be comparable to returning any object plus the fact that the inner instance has a special relation to the outer instance. However, you'd probably not be able to directly use that special relation anyways.

Edit:

As others pointed out already InnerClass might be a super class extended by other inner classes. This would allow you to return any class, that extends that class.

If you'd use an interface, you aren't restricted to inner classes only, since for this restriction you'd need non-static inner interfaces. However, inner interfaces are static by default.

I would rather define an (inner) interface, let all inner class implement it, and then :

Class<OuterClass.MyInterface> someMethod();

This would be more type secure than trying to refer to any inner class. And you wouldn't have any problem the day you need another inner class for another usage, or the day you decide to extract a class.

No there isn't. Just as you cannot reference packages with wildcards:

Class<com.example.*> some_method();
Class<com.example.?> some_method();

The use cases for such declarations would be so limited, it just wouldn't make it into the JLS. Note, you cannot use such "location match types" outside the scope of generics either. Eg you cannot declare:

void some_method(OuterClass.*  argument);
void some_method(com.example.* argument);

You can define marker interface and Implement it by Inner class.

<T implements CustomMarkerInterface> Class<T> some_method()

So this would be applicable to all inner classes of OuterClass

public class Outer {

    public class Inner implements CustomMarkerInterface{

    }

    public class Inner1 implements CustomMarkerInterface{

    }

    public class Inner2 implements CustomMarkerInterface{

    }

}

Class<InnerClass> is allowed in java. Are you looking for something specific?

public class Client
{
interface InnerType
{
}
public class InnerClass implements InnerType
{
}
public Class<? extends Client.InnerType> test()
{
    return InnerClass.class;
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM