简体   繁体   中英

import a java class from a java file which contains multiple classes

i am going through a situation where i have created multiple classes for custom exception in a single java file. as follow

    public class IllegalArgumentException extends Throwable {
        public IllegalArgumentException(String exceptionString) {
            super(exceptionString);
        }
    }

    class InvalidDirectoryException extends Throwable {
        public InvalidDirectoryException(String exceptionString) {
            super(exceptionString);
        }
    }

    class InvalidJsonFormatException extends Throwable {
        public InvalidJsonFormatException(String exceptionString) {
            super(exceptionString);
        }
    }

    class InvalidFileTypeException extends Throwable {
        public InvalidFileTypeException(String exceptionString) {
            super(exceptionString);
        }
    }

when I try to import one of the class then it is not resolving. I am only able to import IllegalArgumentException class. I dont want to make multiple java file for each class. So is there way to do it?

I dont want to make multiple java file for each class.

You have to if you want to access them from other packages. In Java, every file must have exactly one public class. That is a rule. There could be valid reasons why you don't want a separate file for each class, but Java doesn't care about that.

You could try making each of them static inner classes in a single outer class, and then using import static , but that is a bad practice, as you would be abusing the intended purpose of inner classes, so I don't encourage using that method. But you could.

Create one general public class and put all other classes as inner classes inside the main public class.

Example:

public class AllExeptions{

   class IllegalArgumentException extends Throwable {
        public IllegalArgumentException(String exceptionString) {
            super(exceptionString);
        }
    }

    class InvalidDirectoryException extends Throwable {
        public InvalidDirectoryException(String exceptionString) {
            super(exceptionString);
        }
    }

    class InvalidJsonFormatException extends Throwable {
        public InvalidJsonFormatException(String exceptionString) {
            super(exceptionString);
        }
    }

    class InvalidFileTypeException extends Throwable {
        public InvalidFileTypeException(String exceptionString) {
            super(exceptionString);
        }
    }
}

If you are not familiar with the Java inner class, then I recommend you this nince inner class tutorial by TutorialsPoint: https://www.tutorialspoint.com/java/java_innerclasses.htm

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