简体   繁体   中英

Java: Importing Library to Multiple Classes

I've been searching for an answer on StackOverflow and Google . I've done my legwork before asking.

If I'm importing a library into a Java program and want it available in the different classes, do I need to import it to each one manually or is there some way to do this globally?

So far I've been doing what I show below as an example, but it feels a bit 'clunky' and not optimal:

MainProgram:

import java.util.Scanner;
public class MainProgram
{
    public static void main(String[] args)
    {
        Scanner keyboard = new Scanner(System.in);
        Gets getIn = new Gets();

        System.out.print("Enter a string: ");
        String fromKey = getIn.first(keyboard);
        System.out.println(fromKey);
    }
}

Gets.java:

import java.util.Scanner;

public class Gets
{
    public String first(Scanner keyboard)
    {
        String result = keyboard.nextLine();
        return result;
    }
}

As stated above this feels clunky.

Is there any way to have this work with just having to import the libraries into the MainProgram.java file and have them imported to each class that is called (obviously the type would still need to be mentioned in the methods, but that's minor)?

I can see problems arising if the classes are then used in another program that doesn't import the same libraries, however that seems minor with proper commenting.

You have to import it for every class file.

Notice the 'file': you can have multiple classes in one file but you'll only have to import once.

You have to import to every class.

However, doing this with a modern IDE like Eclipse is pretty simple, such that I barely notice it.

Just start typing the class name in the method/declaration/wherever you're using it, and it should pop up an auto-complete-type-thingey ( Ctrl + space to force it) that'll let you choose which import you want.

Yes you have to import it for every class. Like Taylor said, using eclipse makes it alot easier. A shortcut in eclipse would be to write out the Scanner code line and when you get that read underline error, press ctrl - shift - o for 'organize imports'. This will automatically type in the import for you at the top of file in an organized alphabetized way.

是的,您必须为要使用这些库的每个类导入它

As others are saying, You have to import it for every class that you want to use those libraries , however you may want to look at some inheritance (super-class) that will encapsulate this logic for you.

Eg MyScanner extends Scanner

with MyScanner being used in all of your classes and it having methods that return only the results

Eg List<String> getAllLines ();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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