简体   繁体   English

及格课程 <?> cls作为方法参数?

[英]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. 我正在尝试编写一种方法,该方法将使我的主要对象传递两个参数:一个Talker对象实例,一个cls类对象代表侦听器应该从中扩展以便接收消息的类型。 I'm very new to Java and could use some help with this. 我是Java的新手,可以在此方面提供一些帮助。

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: 不知道如何完成此操作,或如何从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. @BornToCode关于调用该方法是正确的,但是您要使用该方法实现的目标仍然有些错误。

cls.isAssignableFrom(cls.getSuperclass())

will always return false. 将始终返回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. 我不明白cls应该代表什么。 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. 供您参考, cls.isAssignableFrom(cls.getSuperclass())将始终返回false。 The documentation of isAssignableFrom says: isAssignableFrom文档说:

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. 确定此Class对象表示的类或接口是否与指定的Class参数表示的类或接口相同,或者是该类或接口的超类或超接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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