如何从 Java 堆栈中提取信息作为单独的数据类型并在方法调用中使用 [英] How to extract information from Java stack as individual data types and use in method call

查看:69
本文介绍了如何从 Java 堆栈中提取信息作为单独的数据类型并在方法调用中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过创建 2 个子类型的堆栈来实现撤消功能.我有一堆父类型 UserEntry,其中包含两个子类型 Assign 和 RelEntry.Assign 和 RelEntry 都是用于将值(数字和关系)插入到网格表中的类.有一个方法调用将值作为它们各自的子类型插入表中,例如 assignToTable()RelEntryToTable().我正在尝试使用一种可以从父堆栈调用这两种子类型的多态方法,例如.

I am trying to implement an undo feature by creating a stack of 2 subtypes. I have a stack of parent type UserEntry holding two child types Assign and RelEntry. Assign and RelEntry is both classes used to insert values (number and relationship) into a grid table. There is a method call to insert the values into the table as their respective subtypes for example assignToTable() and RelEntryToTable(). I am trying to use a polymorphic method that can call both of these subtypes from the parent stack eg.

parentStack.assignAndRelEntryToTable();

在为 UserEntry 创建抽象类时,我尝试了一个 addToPuzzle() 方法,然后我在两个子类中都实现了该方法,但是在尝试调用 using 时

When making the abstract class for UserEntry I have tried an addToPuzzle() method which I then implemented in both child classes however when trying to call using

for (UserEntry ue : stack){
    puzzle.addToPuzzle(ue)
}

方法调用需要一个特定于每个子类的方法.我已经尝试为每个子类创建一个方法调用,但无法从子类中引用拼图本身.

The method call requires a method specific to each sub-class. I've tried creating a method call for each subclass but the puzzle itself cannot be referenced from the sub-classes.

这里有 4 个类一起工作:UI、RelEntry、UserEntry 和 Assign.我正在尝试为 UI 类中的每个循环创建它们,因为它包含拼图变量.

There are 4 classes working together here: UI, RelEntry, UserEntry, and Assign. I am trying to create them for each loop within the UI class as this contains the puzzle variable.

推荐答案

如果我正确理解您的问题,您正在寻找 instanceof.它让你检查一个对象是否是给定的类型.使用它,您可以确定 UserEntry 的子类型,转换为所需的子类型并相应地调用您的方法之一.像这样:

If I understand your question correctly, you're looking for instanceof. It let's you check if an object is of given type. Using it you can determine subtype of the UserEntry, cast to desired subtype and call one of your methods accordingly. Something like so:

for (UserEntry ue : stack){
    if(ue instanceof Assign){
        Assign assign = (Assign) ue;
        puzzle.assignToTable(assign );
    } else if(ue instanceof RelEntry){
        RelEntry relEntry = (RelEntry) ue;
        puzzle.relEntryToTable(relEntry);
    }
}

这篇关于如何从 Java 堆栈中提取信息作为单独的数据类型并在方法调用中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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