反射:在不使用instanceof的情况下将对象强制转换为子类 [英] Reflection: cast an object to subclass without use instanceof

查看:162
本文介绍了反射:在不使用instanceof的情况下将对象强制转换为子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的接口/类:

I have this simple interface/class:

public abstract class Message {}

public class Message1 extends Message {}

public class Message2 extends Message {}

和实用程序类:

public class Utility {
    public void handler(Message m) {
        System.out.println("Interface: Message");
    }

    public void handler(Message1 m) {
        System.out.println("Class: Message1");
    }

    public void handler(Message2 m) {
        System.out.println("Class: Message2");
    }
}

现在,主要类:

public static void main(String[] args) {

    Utility p = new Utility();

    Message1 m1 = new Message1();
    p.handler(m1);

    Message m = (Message) m1;
    p.handler(m);

}

输出

> Class: Message1
> Interface: Message

我想 p.handler(m)调用方法 p.handler(m:Message1)

我不想使用manual命令 instanceof 因为我有很多情况:

I don't want use the "manual" command instanceof because I have many cases:

if(m instance of Message1)
p.handler((Message1)m)
else if (m instanceof Message2)
p.handler((Message2)m)
...






如果我打电话给 m。 getClass()我获取mypackage.Message1,所以子类而不是超类。


If I call m.getClass() I obtain "mypackage.Message1", so the subclass and not the superclass.

我尝试使用这段代码(使用反射) :

I try with this code (use reflection):

p.handler(m.getClass().cast(m));

但输出是

> Interface: Message

所以,这是我的问题。我会做一个超类对象的运行时强制转换为subclassobject而不使用code commandistanceof。

So, this is my problem. I would do a runtime cast of superclass object to subclassobject without use the "code command" istanceof.

我会这样一个正确的命令:

I would a right command like this:

p.handler((m.getclass)m);

我如何获得它?这可能吗?

How can I obtain it? It's possible?

推荐答案

Java将根据编译时已知的信息调用该方法。你可以做的是向接口添加一个方法,为该对象调用正确的处理程序方法。

Java will call the method on the basis of information known at compile time. What you could do is add a method to the interface that calls the correct handler method for the object.

public abstract class Message {

    public abstract void callHandler(Utility utility);

}

public class Message1 extends Message{

    public void callHandler(Utility utility) {
        utility.handler(this);
    }
}

您对处理程序的调用变为:

Your calls to the handler become:

Message m=(Message) m1;
m.callHandler(p);

现在调用Utility :: handler(Message1),即使main中的引用是类型为消息界面。

which now calls Utility::handler(Message1) even though the reference in main is of type of the Message interface.

这篇关于反射:在不使用instanceof的情况下将对象强制转换为子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆