简体   繁体   中英

Passing Class<?> cls as a method parameter?

I'm having trouble completing this method.

I am trying to write a method that will let my main pass two parameters: a Talker object instance and cls a Class object representing the type which the Listener should extend from in order to receive the message. I'm very new to Java and could use some help with this.

Here's the code for the method:

public void sMessage(Talker talker, Class<?> cls) {
    for ( Listener l : mParticipants)
    {
        if (cls.isAssignableFrom(cls.getSuperclass())) {
            l.onMessageReceived(talker.getMessage());   
        }
    }
}

Not sure how I should complete this, or how to make a call from main:

singletonDemo.sMessage(demoTalker, Class?);

Not really following the examples I've seen so far. Any suggestions?

@BornToCode is correct about calling the method, but what you want to achieve with the method is still slightly wrong.

cls.isAssignableFrom(cls.getSuperclass())

will always return false. This is because you cannot take a parent class and assign it to the child class. I believe what you are looking for is a way to check if the listener extends the class specified. You can do this by getting the class of the listener.

cls.isAssignableFrom(l.getClass())

or more simply

cls.isInstance(l)

I do not understand what cls should represent. However, you should get something like:

singletonDemo.sMessage(demoTalker, SomeClass.class);

or:

singletonDemo.sMessage(demoTalker, someClassInstance.getClass());

For your information, cls.isAssignableFrom(cls.getSuperclass()) will always return false. The documentation of isAssignableFrom says:

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter.

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