简体   繁体   English

如何从另一个类调用方法

[英]How to call method from another class

It has been a long time since I used java and I have run into a problem. 自从我使用Java以来​​已经有很长时间了,我遇到了一个问题。 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. 问题是我需要从另一个类“ Function.class”中调用方法“ shippingCost”。这是已编译的代码,没有源代码。

How do I call this from my class, "FunctionTest.java" inside of the public static void main. 如何从公共static void main内部的类“ FunctionTest.java”中调用此方法。

Thanks! 谢谢!

The class, and the error msg. 该类,以及错误消息。

类

在此处输入图片说明

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. 进一步的帮助将给我们错误消息,以便我们知道您实际上遇到的是哪种类型的问题。

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. 您的命名方案有很多不足之处。

  1. Put the 'Function.class' file into the Libraries folder of your project. 将“ Function.class”文件放入项目的Libraries文件夹中。
  2. Put an import statement with the correct package of 'Function' class into your FunctionTest.java file: import xx.xx.Function; 将带有正确的“ Function”类包的import语句放入FunctionTest.java文件中: import xx.xx.Function; (Netbeans should be able to do that automatically on command.) (Netbeans应该能够根据命令自动执行此操作。)

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

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