Reputation: 1022
If I have two objects, in and out, is it possible to make those objects static or available every where? So that no matter where I am in a program I can type
out.println("Hello!");
and it functions without having to pass in and out into different objects like so?
happyCat(BufferedReader in, PrintStream out);
Please let me know if this is possible.
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
PrintStream out = new PrintStream(server.getOutputStream());
Upvotes: 0
Views: 1048
Reputation: 120516
No. In every source file, you will either have to statically import your in
and out
:
import static pkg.MyGlobals.in;
import static pkg.MyGlobals.out;
or you will have to qualify uses as in
pkg.MyGlobals.out.method(...)
There is no way to define new packages like java.lang
which are implicitly imported, and there are no classes whose static members are implicitly imported.
Only the methods defined on Object
are available unqualified everywhere and that is only because they are inherited in every context that can contain code that could reference them.
Section 6.5.6.1 Simple Expression Names explains how simple names like in
and out
are matched to fields of objects:
If an expression name consists of a single Identifier, then there must be exactly one declaration denoting either a local variable, parameter, or field visible (§6.4.1) at the point at which the Identifier occurs. Otherwise, a compile-time error occurs.
Following links from that starting point should convince you that there are no hidden mechanisms for this.
Upvotes: 0
Reputation: 2441
You can change the default in and out streams of the Java environment by calling System.setIn()
and System.setOut()
, see javadoc for class System here. When any piece of code references the default streams, they will be "redirected" to your instances.
System.setOut(myOutput);
System.setIn(myInput);
...
System.out.println("hello"); // This will print to your output stream
System.in.read(); // This will read from your input stream
Upvotes: 1
Reputation: 5233
You can create a class Streams and use static :
class Streams {
// I don't know where "server" come from
public static BufferedReader in = ...
public static PrintStream out = ...
}
an then use :
Streams.in and Streams.out
Upvotes: 1