In Vb.net, we have something called a "Module" that provides a global scope whereby static functions in the module is visible throughout the entire project.
Is there such a functionality in Java ? (i.e. adding static methods that are available to multiple packages/files/classes without having the need to import .* )
Ok I am aware this is a functionality that would cause alot of debate, but really the point of this thread is not to debate about this functionality.
To answer literally, no, there's no real "global" in Java. But you don't need to import, particularly not import .*.
The code below illustrates that an import is not required but it's only really part of the answer.
package org.example.pkg.foo;
public class Foo {
public static void doSomething();
}
package org.example.pkg.bar;
public class Bar {
public void bar() {
org.example.pkg.foo.Foo.doSomething();
}
}
In Java, types, such as classes and interfaces, are defined in terms of the ClassLoader which loaded them. You can have multiple class loaders, which implies that multiple copies of the same class can be loaded. The obvious extension of this is that multiple classes with the same qualified name (package + class) can be loaded, and there's no inherent requirement that they are related.
OSGi is an example of this, where each bundle has it's own class loader, and as a result you can have multiple versions of the same class loaded at the same time.
How does this relate to the question? Well, without accurately identifying the class you want to reference it's not possible to accurately identify the method or member you want to reference. The import, or FQN referencing does that.
No, don't think so. Static imports can make it a bit less painful/verbose to use such methods, but it's generally advised to be careful with them.
Not without the import. You can declare public static methods that are accessible from anywhere in the project, but you still have to either import the class or use fully qualified class path when you use it.
public methods are visible throughout the project
however if you want to dispense with the imports you can make the path explicit
my.package.UtilClass.methodIWannaCall(someArg);
No. Import is needed for any static method to be visible.(which is a good thing).
As others mentioned, Java IDEs do this job for us.
Related
Ok, let me start it with the following example to get a brief example
public class ClassA{
______ static final String MODULE = "[ClassA]";
}
in the blank space, I came across many code snippet it has some times public or protected or private but could not understand the which one is the best and why?.I know protected is best for subclass implementation but then subclass to has MODULE variable.
basically MODULE is used in logging activities like for example
System.out.println(MODULE+"given message");
in-short which is best way to use for accessing?
Like anything, you should give it the strictest access level that makes sense.
If it will only be used inside the class, use private. If it will only be used inside the package, use package access. If it could be used in subclasses, use protected. If it could be used by anyone, use public.
This applies to every class member in every programming language - it is by no means specific to fields named MODULE in Java.
Basically MODULE is used in logging activities...
Then I would suggest to make it private, because it will not be used outside the class (assuming that other classes have similar static constants).
In Python you can do a:
from a import b as c
How would you do this in Java, as I have two imports that are clashing.
There is no import aliasing mechanism in Java. You cannot import two classes with the same name and use both of them unqualified.
Import one class and use the fully qualified name for the other one, i.e.
import com.text.Formatter;
private Formatter textFormatter;
private com.json.Formatter jsonFormatter;
As the other answers already stated, Java does not provide this feature.
Implementation of this feature has been requested multiple times, e.g. as JDK-4194542: class name aliasing or JDK-4214789: Extend import to allow renaming of imported type.
From the comments:
This is not an unreasonable request, though hardly essential. The occasional
use of fully qualified names is not an undue burden (unless the library
really reuses the same simple names right and left, which is bad style).
In any event, it doesn't pass the bar of price/performance for a language
change.
So I guess we will not see this feature in Java anytime soon :-P
It's probably worth noting that Groovy has this feature:
import java.util.Calendar
import com.example.Calendar as MyCalendar
MyCalendar myCalendar = new MyCalendar()
Java doesn't allow you to do that. You'll need to refer to one of the classes by its fully qualified name and only import the other one.
Today I filed a JEP draft to OpenJDK about this aliasing feature. I hope they will reconsider it.
If you are interested, you can find a JEP draft here: https://gist.github.com/cardil/b29a81efd64a09585076fe00e3d34de7
It's ridiculous that java doesn't have this yet. Scala has it
import com.text.Formatter
import com.json.{Formatter => JsonFormatter}
val Formatter textFormatter;
val JsonFormatter jsonFormatter;
Unless there are problems with non-default constructors you can always do this (while we all wait for the Java language specification to catch up):
public class YaddaYadda
{
private static class ZU extends eu.zrbj.util.ZrbjUtil_3_0 { }
public void foo (String s)
{
if (ZU.isNullOrEmpty(s))
{
// ...
For project-wide use the 'import' class can go into a separate class file, giving a single point of definition for the import.
This is a lifesaver especially with regard to 'library' classes, meaning collections of static utility functions. For one thing it gives you the ability to version these beasts - as shown in the example - without major inconvenience for the user.
Actually it is possible to create a shortcut so you can use shorter names in your code by doing something like this:
package com.mycompany.installer;
public abstract class ConfigurationReader {
private static class Implementation extends com.mycompany.installer.implementation.ConfigurationReader {}
public abstract String getLoaderVirtualClassPath();
public static QueryServiceConfigurationReader getInstance() {
return new Implementation();
}
}
In that way you only need to specify the long name once, and you can have as many specially named classes you want.
Another thing I like about this pattern is that you can name the implementing class the same as the abstract base class, and just place it in a different namespace. That is unrelated to the import/renaming pattern though.
Since java.lang.* classes are implicitly imported into every source file, this makes it harder for a developer to use these class names in their own namespaces. For example, someone may want to create a Compiler class, since it is a common name and java.lang.Compiler is a rarely used. By doing so, the developer would have to use its fully qualified name, like com.my.organization.my.very.long.package.name.Compiler, every time, which does not improve code readability. Explicitly importing this class would be very confusing, and changing the name to something more specific is not always an option, because Compiler might be instead an interface for generic anything-to-anything compiler. Thus, in some cases the only option is to add a prefix or a suffix to distinguish the name. Another example I can imagine is a forum application, which may have classes like Author, Post, and yes - Thread. Adding anything to Thread would clearly distinguish it from functionally similar classes. Are there any conventions on class naming in such cases? The least intrusive option I personally see is adding a trailing underscore, like Thread_.
I've generally been able to come up with names that avoided being so generic they conflicted, but even in those situations where you can't, provided your code is in a package, the unqualified name will be the package's class, not the java.lang one:
stuff/Compiler.java:
package stuff;
public class Compiler {
public static long value = 42L;
}
stuff/Foo.java:
package stuff;
public class Foo {
public static void main(String[] args) {
System.out.println(Compiler.value); // <== Compiler is stuff.Compiler
}
}
Running that (java stuff/Foo) prints 42.
Using reflection you can get pretty much everything relating to a class. You can get all the declared methods, fields and classes (and possibly even more), but i couldn't find a way to reflect on a method so i could find out what classes that method might be using.
Essentially i would like to find out all dependencies to other classes that a given class has.
Example:
Given the following code:
import com.yada.yada.yada.SomeClass
public class MyClass
{
public MyClass
{
new SomeClass();
}
}
How can i find out that MyClass is using SomeClass in its constructor?
I was trying to think of a way to get all import statements defined in a class file but i couldn't find anything that way either. But, assuming there's a way to somehow dig up all import statements defined in a class file, how would one find out about classes defined in the same package, which do not require an import statement?
EDIT:
Scenario: The goal is to send the bytecode of this class (MyClass) to another process. This other process then takes in the bytecode and loads the class (MyClass) using class loaders, and so on. The problem is that when i try to create and run an instance of MyClass in the other process it fails because it cannot find a definition for SomeClass.
If SomeClass were a member of MyClass it wouldn't be a problem but since the only reference to it lies in a method, there's no way to get to it via reflection?
I think the closest you can come to getting all of a class's dependencies is by hooking into the class loader mechanism and recording what classes get loaded when the class you're examining is instantiated and its methods are called. Of yourse, you'd transitively also get all the classes that it indirectly depends on, but depending on what you want to do with the information, that may be what you actually need.
But it's impossible to do for all cases (just imagine a method that uses Class.forName() to ask for a random class name every time it's called).
how would one find out about classes defined in the same package
That's actually impossible to do in general, since the class loader concept really only allows asking for a fully qualified class name, and either getting that class or a ClassNotFoundException. Classes can be loaded from a webserver (in the case of applets) or generated on the fly, so you cannot know whether a specific class exists except by asking for it.
You can't (unless you decompile the bytecode). A local variable is not tied to any class instance, and it does not even exist for most of the lifetime of the class or its instances, so you can't access it via reflection.
What are you trying to achieve? Maybe if you tell us about your actual problem, rather than a perceived solution, we are better able to help.
Reflection does not help you here. The only way I can think of that you can achieve this is through a byte code tool like asm.
Create a ClassVisitor that gathers dependencies from
Class declarations
Annotations
Local variable declarations
Field declarations
Method declarations
Method invocations
(have I forgotten anything?)
In Python you can do a:
from a import b as c
How would you do this in Java, as I have two imports that are clashing.
There is no import aliasing mechanism in Java. You cannot import two classes with the same name and use both of them unqualified.
Import one class and use the fully qualified name for the other one, i.e.
import com.text.Formatter;
private Formatter textFormatter;
private com.json.Formatter jsonFormatter;
As the other answers already stated, Java does not provide this feature.
Implementation of this feature has been requested multiple times, e.g. as JDK-4194542: class name aliasing or JDK-4214789: Extend import to allow renaming of imported type.
From the comments:
This is not an unreasonable request, though hardly essential. The occasional
use of fully qualified names is not an undue burden (unless the library
really reuses the same simple names right and left, which is bad style).
In any event, it doesn't pass the bar of price/performance for a language
change.
So I guess we will not see this feature in Java anytime soon :-P
It's probably worth noting that Groovy has this feature:
import java.util.Calendar
import com.example.Calendar as MyCalendar
MyCalendar myCalendar = new MyCalendar()
Java doesn't allow you to do that. You'll need to refer to one of the classes by its fully qualified name and only import the other one.
Today I filed a JEP draft to OpenJDK about this aliasing feature. I hope they will reconsider it.
If you are interested, you can find a JEP draft here: https://gist.github.com/cardil/b29a81efd64a09585076fe00e3d34de7
It's ridiculous that java doesn't have this yet. Scala has it
import com.text.Formatter
import com.json.{Formatter => JsonFormatter}
val Formatter textFormatter;
val JsonFormatter jsonFormatter;
Unless there are problems with non-default constructors you can always do this (while we all wait for the Java language specification to catch up):
public class YaddaYadda
{
private static class ZU extends eu.zrbj.util.ZrbjUtil_3_0 { }
public void foo (String s)
{
if (ZU.isNullOrEmpty(s))
{
// ...
For project-wide use the 'import' class can go into a separate class file, giving a single point of definition for the import.
This is a lifesaver especially with regard to 'library' classes, meaning collections of static utility functions. For one thing it gives you the ability to version these beasts - as shown in the example - without major inconvenience for the user.
Actually it is possible to create a shortcut so you can use shorter names in your code by doing something like this:
package com.mycompany.installer;
public abstract class ConfigurationReader {
private static class Implementation extends com.mycompany.installer.implementation.ConfigurationReader {}
public abstract String getLoaderVirtualClassPath();
public static QueryServiceConfigurationReader getInstance() {
return new Implementation();
}
}
In that way you only need to specify the long name once, and you can have as many specially named classes you want.
Another thing I like about this pattern is that you can name the implementing class the same as the abstract base class, and just place it in a different namespace. That is unrelated to the import/renaming pattern though.