Static import and class file generation - java

If we use static import for a class, will the compiler generate a class file for statically imported class when compiling the actual class?
Ex:
import static com.x.y.util.B.getIds();
public class A {
...
}
When compiler compiles class A, will it generate class files for B as well?

When you use some type in class using key word import or just by full name to it. You must assure that during compilation time, compiler has that both classes in build path.
The static import allow you to access static members of imported class. Nothing more.
class Bar {
public static int getID() {
return -1;
}
}
And for static import
import static Bar.getID;
class Foo {
private void foo() {
int id = getID(); //instead of Bar.getID();
}
}
Read more on Oracle docs

No, import statement does not cause compiler to generate anything. Think about it: how can compiler generate class if it does not have a source code? Compiler by definition translate source code into executable code (or byte code in case of java).
BTW the syntax of static import in your example is not correct. You should not use () in static import:
import static com.x.y.util.B.getIds;

Related

How to import functions from different files in Java [duplicate]

This question already has answers here:
Calling static method from another java class
(3 answers)
Closed 1 year ago.
In java, I know I can use methods from other class by creating that class in my main myClass newClass = new myClass() and then use methods by doing myClass.myMethod(), where myMethod() is defined in myClass.java, but what if I want a file named utils.java that contains a bunch of useful methods, I just want to use a function that there's in this file, is this possible? How can I import and use the functions from that file?
You do not need to "import" the functions, you would need just to create a class that keeps all your needed functions, and import that class.
I am supposing you use an IDE, you could go to your IDE and create a simple class.
e.g:
public class Utils
{
public static int doSmth(/* Your parameters here */)
{
// Your code here
}
public static void yetAnotherFunction(/* Your parameters here */)
{
// Your code here
}
}
The most important keyword here is static, to understand it I suggest you check my answer here: when to decide use static functions at java
Then you import this class to any of your other classes and call the static functions, without creating an Object.
import package.Utils;
public class MainClass
{
public static void main(String[] args)
{
Utils.doSmth();
}
}
You can add at the beginning:
import
like-
import utils;
Assuming it is in the same package as the current class
Else it should be:
import <package name>.<class name>
Yes, you can import methods but there are caveats. The methods are defined on a class. The methods are defined as static. The import employs the keyword static. Keep in mind that importing methods directly can create confusion and complicate debugging. Consider importing the class and invoke the method from the class. When/whether defining a utility class makes sense and how to implement them are separate discussions.
package some.path;
public class MyUtils {
public static int add(int x, int y) { return x + y; }
}
To import the method
package some.other.path;
import static some.path.MyUtils.add; // note keyword static here
public class MyClass {
private int a, b;
public int sum() { return add(a,b); }
}
Or, import the class and use the method statically
package some.other.path;
import some.path.MyUtils;
public class MyClass {
private int a,b;
public int sum() { return MyUtils.add(a,b); }
}

Codemodel does not generate static import

JCodeModel generates an import statement in place of an import static. For example I have a class that has import nz.co.cloudm.cloudserv.api.pojos.core.file.attachment.Attachment.Status instead of import static nz.co.cloudm.cloudserv.api.pojos.core.file.attachment.Attachment.Status so the compiler throws an error. The class Status is an inner enum that lives in the Attachment class as you can see in the import statement.
Do you know any way I can achieve an import static using code model?
Or otherwise how make the member to use the class qualified name?
private nz.co.cloudm.cloudserv.api.pojos.core.file.attachment.Attachment.Status status;
I'm not sure codemodel has the ability to define static imports, as it's an older library. You can use the enum though just through the ref() method since static imports are really just a programmer's convenience:
public class Tester {
public enum Status{
ONE, TWO;
}
public static void main(String[] args) throws JClassAlreadyExistsException, IOException {
JCodeModel codeModel = new JCodeModel();
JClass ref = codeModel.ref(Status.class);
JDefinedClass outputClass = codeModel._class("Output");
outputClass.field(JMod.PRIVATE, ref, "status", ref.staticRef(Status.ONE.name()));
codeModel.build(new StdOutCodeWriter());
}
}
Outputs:
public class Output {
private test.Tester.Status status = test.Tester.Status.ONE;
}

How To Properly Import Methods

I am currently working on understanding how to import other classes from a certain package in Java to another package and that certain class.
I was wondering how would I import a method from a certain class in Java to another one since I obviously can't "extend" that class to gain that method since its in some other package.
Example:
package Responses;
public class Hello {
public static void sayHello() {
System.out.print("HELLO!");
}
}
The question:
How do you import sayHello from the Hello class that's in package Responses.
package Start;
public class Begin {
public static void main(String[] args) {
sayHello();
}
}
I am not extending any classes like I stated above, so please don't suggest that.
Import the class that the function resides in:
import Responses.Hello;
Then you can call the function: Hello.sayHello();
In Java there is no construct to directly import a method, but you can import the class in which it resides.
import static Responses.Hello.sayHello;
Then in your other class you can do:
sayHello();
Note: You can only import methods if they are static.
You either import whole classes (A) or their static members (B).
A:
import responses.Hello;
public class Begin {
String myString = Hello.sayHello();
}
B:
import static responses.Hello.sayHello; // To import all static members use responses.Hello.*;
public class Begin {
String myString = sayHello();
}
What oracle says about the usage of static imports:
So when should you use static import? Very sparingly! Only use it when you'd otherwise be tempted to declare local copies of constants, or to abuse inheritance (the Constant Interface Antipattern). In other words, use it when you require frequent access to static members from one or two classes. If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from. Importing all of the static members from a class can be particularly harmful to readability; if you need only one or two members, import them individually. Used appropriately, static import can make your program more readable, by removing the boilerplate of repetition of class names.
Find the whole thing here.
PS
Please use naming convention for your packages:
Package names are written in all lower case to avoid conflict with the names of classes or interfaces.
That's from here
One way is to make your sayHello() method public static. Like
public class Hello {
public static void sayHello() {
System.out.print("HELLO!");
}
}
Then in your Begin class, you can call sayHello using Hello. Of course you should import that Hello class first if they are not under the same package.
public static void main(String[] args) {
Hello.sayHello();
}

Why can't find the value in Java class?

Here is the problem, when I defined a interface like this:
package mypackage;
public interface Ainterface {
int VAL = 6;
}
and then I defined a class like:
public class Aclass implements Ainterface {
private String[] str = new String[VAL];
public static void main(String[] args) { ... }
}
When I compiler the program, there show the error message: can't find the symbol "VAL".
symbol: VAL
position: Aclass
When I compiler the program, there show the error message: can't find the symbol "VAL".
Is that the only compiler error message? If so, please goto wtf;.
If not, are any of the other compiler error messages equivalent to the compiler saying that it also can not find Ainterface? If so, your issue is simple. It appears that either Aclass is in a different package, or you intended for it to be in the same package. In the former case, you need import mypackage.Ainterface. The latter case, you need to put Aclass in the same package with package mypackage.
wtf:
Can you please produce the smallest working example that shows the issue? Here's the problem: I have to work really hard to reproduce your issue, and it's very unlikely to be the issue that you're experiencing.
There are few possibilities.
a. Ainterface and Aclass are in the same package. In this case, there should be no issue.
Ainterface.java:
package mypackage;
public interface Ainterface {
int VAL = 6;
}
Aclass.java
package mypackage;
public class Aclass implements Ainterface {
private String[] str = new String[VAL];
public static void main(String[] args) { }
}
b. Ainterface and Aclass are in different packages. In this case, there must be an import mypackage.Ainterface import statement in the java source file for Aclass. In this case, there should be no issue.
package mypackage;
public interface Ainterface {
int VAL = 6;
}
Aclass.java:
package myotherpackage;
import mypackage.Ainterface;
public class Aclass implements Ainterface {
private String[] str = new String[VAL];
public static void main(String[] args) { }
}
In both cases, the code will compile as is. Neither of these produce the issue, and they are the only two possibilities that make sense. There is a third possibility. Please tell me it is not this. You have two Ainterface defined, one in one package, one in another and Aclass sits in the same package as one of the definitions that doesn't define VAL:
Ainterface.java:
package mypackage;
public interface Ainterface {
int VAL = 6;
}
Ainterface.java:
package myotherpackage;
public class Ainterface {
}
Aclass.java:
package myotherpackage;
public class Aclass implements Ainterface {
private String[] str = new String[VAL];
public static void main(String[] args) { }
}
This will produce the error. And, to be clear, this can happen on accident. Say you define Ainterface and put it in mypackage. Say you define Aclass and you don't put it in the same package and you forget to import mypackage.Ainterface. If you're using an IDE like Eclipse, you'll get an error message that Ainterface can not be resolved to a type and you'll have three quick fixes available: "Import 'Ainterface' (mypackage)", "Create interface 'Ainterface'", "Fix project setup...". If you accidentally clicked the second option, you'll end up in this case. But that's just silly, that can not be what you intended. So, help us help you.
You should refer VAL in a static way as all the variables defined in an interface is by default public, static and final. This should work:
private String[] str = new String[Ainterface.VAL];
An interface can contain constant declarations in addition to method declarations. All constant values defined in an interface are implicitly public, static, and final. Once again, these modifiers can be omitted. Check this for more details.
So in order to access it use Ainterface.VAL(Since variables defined in interface are static).
private String[] str = new String[Ainterface.VAL];
This works fine if present in same package but if you want to that files to be in different package then you can do either of things.
Option 1:
Import mypackage;
in Aclass.java file
Option 2:
Or change VAL with Ainterface.VAL then statement become
private String[] str = new String[Ainterface.VAL];

What does the "static" modifier after "import" mean?

When used like this:
import static com.showboy.Myclass;
public class Anotherclass{}
what's the difference between import static com.showboy.Myclass and import com.showboy.Myclass?
See Documentation
The static import declaration is
analogous to the normal import
declaration. Where the normal import
declaration imports classes from
packages, allowing them to be used
without package qualification, the
static import declaration imports
static members from classes, allowing
them to be used without class
qualification.
So when should you use static import?
Very sparingly! Only use it when you'd
otherwise be tempted to declare local
copies of constants, or to abuse
inheritance (the Constant Interface
Antipattern). In other words, use it
when you require frequent access to
static members from one or two
classes. If you overuse the static
import feature, it can make your
program unreadable and unmaintainable,
polluting its namespace with all the
static members you import. Readers of
your code (including you, a few months
after you wrote it) will not know
which class a static member comes
from. Importing all of the static
members from a class can be
particularly harmful to readability;
if you need only one or two members,
import them individually. Used
appropriately, static import can make
your program more readable, by
removing the boilerplate of repetition
of class names.
There is no difference between those two imports you state. You can, however, use the static import to allow unqualified access to static members of other classes. Where I used to have to do this:
import org.apache.commons.lang.StringUtils;
.
.
.
if (StringUtils.isBlank(aString)) {
.
.
.
I can do this:
import static org.apache.commons.lang.StringUtils.isBlank;
.
.
.
if (isBlank(aString)) {
.
.
.
You can see more in the documentation.
Static import is used to import static fields / method of a class instead of:
package test;
import org.example.Foo;
class A {
B b = Foo.B_INSTANCE;
}
You can write :
package test;
import static org.example.Foo.B_INSTANCE;
class A {
B b = B_INSTANCE;
}
It is useful if you are often used a constant from another class in your code and if the static import is not ambiguous.
Btw, in your example "import static org.example.Myclass;" won't work : import is for class, import static is for static members of a class.
The basic idea of static import is that whenever you are using a static class,a static variable or an enum,you can import them and save yourself from some typing.
I will elaborate my point with example.
import java.lang.Math;
class WithoutStaticImports {
public static void main(String [] args) {
System.out.println("round " + Math.round(1032.897));
System.out.println("min " + Math.min(60,102));
}
}
Same code, with static imports:
import static java.lang.System.out;
import static java.lang.Math.*;
class WithStaticImports {
public static void main(String [] args) {
out.println("round " + round(1032.897));
out.println("min " + min(60,102));
}
}
Note: static import can make your code confusing to read.
the difference between "import static com.showboy.Myclass" and "import com.showboy.Myclass"?
The first should generate a compiler error since the static import only works for importing fields or member types. (assuming MyClass is not an inner class or member from showboy)
I think you meant
import static com.showboy.MyClass.*;
which makes all static fields and members from MyClass available in the actual compilation unit without having to qualify them... as explained above
The import allows the java programmer to access classes of a package without package qualification.
The static import feature allows to access the static members of a class without the class qualification.
The import provides accessibility to classes and interface whereas static import provides accessibility to static members of the class.
Example :
With import
import java.lang.System.*;
class StaticImportExample{
public static void main(String args[]){
System.out.println("Hello");
System.out.println("Java");
}
}
With static import
import static java.lang.System.*;
class StaticImportExample{
public static void main(String args[]){
out.println("Hello");//Now no need of System.out
out.println("Java");
}
}
See also : What is static import in Java 5
Say you have static fields and methods inside a class called MyClass inside a package called myPackage and you want to access them directly by typing myStaticField or myStaticMethod without typing each time MyClass.myStaticField or MyClass.myStaticMethod.
Note : you need to do an
import myPackage.MyClass or myPackage.*
for accessing the other resources
The static modifier after import is for retrieving/using static fields of a class. One area in which I use import static is for retrieving constants from a class.
We can also apply import static on static methods. Make sure to type import static because static import is wrong.
What is static import in Java - JavaRevisited - A very good resource to know more about import static.

Categories

Resources