简体   繁体   English

从另一个java类调用静态方法

[英]Calling static method from another java class

I've recently switched from working in PHP to Java and have a query. 我最近从使用PHP转向Java并进行了查询。 Want to emphasise I'm a beginner in Java. 想强调我是Java的初学者。

Essentially I am working in File A (with class A) and want to refer to a static method saved in File B (class B). 基本上我正在使用文件A(使用类A)并且想要引用保存在文件B(类B)中的静态方法。 Do I need to make any reference to File B when working with class A? 在使用A类时,是否需要对文件B进行任何引用? (I'm thinking along the lines of require_once in PHP) My code in Class A is as follows: (我正在思考PHP中的require_once)我在A类中的代码如下:

Public class A{
String[] lists = B.staticMethod();
}

Eclipse is not recognising B as a class. Eclipse没有将B识别为类。 Do I need to create an instance of B in order to access the static method. 我是否需要创建B的实例才能访问静态方法。 Feel like I'm really overlooking something and would appreciate any input. 感觉我真的忽略了什么,并会欣赏任何输入。

Ensure you have proper access to B.staticMethod. 确保您有权访问B.staticMethod。 Perhaps declare it as 也许宣布为

public static String[] staticMethod() {
    //code
}

Also, you need to import class B 此外,您需要导入B类

import foo.bar.B; // use fully qualified path foo.bar.B

public class A {
    String[] lists = B.staticMethod();
}

You don't need to create an instance of the class to call a static method, but you do need to import the class. 您不需要创建类的实例来调用静态方法,但您确实需要导入该类。

package foo;

//assuming B is in same package
import foo.B;

Public class A{
  String[] lists = B.staticMethod();
}

Java has classloader mechanism that is kind of similar to PHP's autoloader. Java具有类似于PHP的自动加载器的类加载器机制。 This means that you don't need anything like a include or require function: as long as the classes that you use are on the "classpath" they will be found. 这意味着你不需要像includerequire函数这样的东西:只要你使用的类在“类路径”上就可以找到它们。

Some people will say that you have to use the import statement . 有些人会说你必须使用import语句 That's not true; 这不是真的; import does nothing but give you a way to refer to classes with their short names, so that you don't have to repeat the package name every time. import只会为您提供一种使用短名称引用类的方法,这样您就不必每次都重复包名。

For example, code in a program that works with the ArrayList and Date classes could be written like this: 例如,使用ArrayListDate类的程序中的代码可以这样写:

java.util.ArrayList<java.util.Date> list = new java.util.ArrayList<>();
list.add(new java.util.Date());

Repeating the package name gets tiring after a while so we can use import to tell the compiler we want to refer to these classes by their short name: 重复包名称会在一段时间后变得很累,所以我们可以使用import来告诉编译器我们想通过它们的短名称来引用这些类:

import java.util.*;
....
ArrayList<Date> list = new ArrayList<>();
list.add(new Date());

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

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