是否可以将Class作为参数传递 [英] Is it possible to pass a Class as a parameter

查看:72
本文介绍了是否可以将Class作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定它是否可行,但我一直试图将一个类作为参数传递。运行代码后,我得到一个本机方法错误,我想要做的是传递一个类的集合,并使用堆栈执行一个名为execute的特定方法。



< pre lang =java> import java.util.EmptyStackException;
import java.util.Stack;


public class 树{
Stack<节点> nodeStack = new Stack< Node>();

public Tree(){
nodeStack = null;
}
void setTasks(节点节点){

try {



nodeStack.push(Nodes);
}
catch (例外e){
e.printStackTrace();
}

}
void runTasks(){

节点node =(节点)nodeStack.peek();
if (nodeStack!= null){
node.execute();


}

else {
throw new EmptyStackException();
}
}


}





 public abstract class Node {

public boolean condition(){
return false;
}


public void execute(){

}




}

解决方案

是的,有可能。

Java Reflection API - 它将指导您完成。


我想你会遇到一些麻烦,因为你试图将一个抽象类的对象推入堆栈......一个抽象类不能被实现。此外,你的标题是''class'',它应该是''对象''。我同意查看反射API。


Im not sure if its possible, but I have been trying to pass a class as a parameter. After running the code i get a native methods error , what im trying to do is pass a collection of classes and execute a specific method called execute using a stack.

import java.util.EmptyStackException;
import java.util.Stack;


public class Tree {
    Stack<Node> nodeStack = new Stack<Node>();

    public Tree(){
         nodeStack = null;
    }
    void setTasks( Node  Nodes){

        try{



            nodeStack.push(Nodes);
        }
        catch (Exception e){
            e.printStackTrace();
        }

    }
     void runTasks(){

       Node node = (Node) nodeStack.peek();
        if(nodeStack!=null){
              node.execute();


        }

        else{
            throw new EmptyStackException();
        }
    }


}



public abstract class  Node {

    public boolean condition(){
        return false;
    }


    public void execute(){

    }




}

解决方案

YES, it is possible.
Java Reflection API - that will guide you through.


I think you''ll run into some trouble because you''re trying to push an object of a abstract class onto the stack... An abstract class can''t be instansiated. Also, you''re title reads ''class'', it should be ''object''. I do agree to look at the reflection API.


这篇关于是否可以将Class作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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