java 如何从另一个类调用方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9898009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call method from another class
提问by Meowbits
It has been a long time since I used java and I have run into a problem. I need to load test cases from a file and then run them. The problem is that I need to call a method "shippingCost" from another class "Function.class" This is a compiled code, no source.
自从我使用java已经很长时间了,我遇到了一个问题。我需要从文件加载测试用例,然后运行它们。问题是我需要从另一个类“Function.class”调用一个方法“shippingCost”这是一个编译代码,没有源代码。
How do I call this from my class, "FunctionTest.java" inside of the public static void main.
我如何从我的类中调用它,“FunctionTest.java”在 public static void main 中。
Thanks!
谢谢!
The class, and the error msg.
类和错误消息。
回答by digitaljoel
You don't need the source in order to call the method, all you need is the compiled class. As long as you can access the method (generally if it's public) then you should be able to call it. An IDE like eclipse will even be able to help you find out which methods are available on an instance of the class.
您不需要源代码来调用该方法,您只需要编译后的类。只要您可以访问该方法(通常如果它是公共的),那么您就应该能够调用它。像 eclipse 这样的 IDE 甚至可以帮助您找出在类的实例上可用的方法。
So in the simplest case, you just create an instance of the class and then call the method.
因此,在最简单的情况下,您只需创建该类的一个实例,然后调用该方法。
Function func = new Function();
func.callMethod();
Further help would be giving us the error message so we would know which type of problem you are actually having.
进一步的帮助将向我们提供错误消息,以便我们知道您实际遇到的是哪种类型的问题。
回答by Ozan
- Put the 'Function.class' file into the Libraries folder of your project.
- Put an import statement with the correct package of 'Function' class into your FunctionTest.java file:
import xx.xx.Function;
(Netbeans should be able to do that automatically on command.)
- 将“Function.class”文件放入项目的 Libraries 文件夹中。
- 将带有正确的“Function”类包的导入语句放入您的 FunctionTest.java 文件中:
import xx.xx.Function;
(Netbeans 应该能够根据命令自动执行此操作。)
回答by duffymo
You need to get a reference to an instance of the object and invoke its methods.
您需要获取对对象实例的引用并调用其方法。
Function function = new Function();
function.myFunction();
Your naming scheme leaves a lot to be desired.
您的命名方案还有很多不足之处。