Is is possible to change entry point of java program from main(default) to other?
If I write code
public class TestWithoutMain {
static {
System.out.println("hello bristy!!!");
}
}
I am not able to run code in eclipse. If i add main method to above code
public class TestWithoutMain {
static {
System.out.println("hello bristy!!!");
}
public static void main(String[] args) {
}
}
It is printing hello bristy!!!.
The basic concept is the main class is searched first and than and only than it is executed via main. So the first answer is NO. You cannot change the entry point.
Now in your code you have a static System.out.prinln block. In java, static contents are loaded when the class is loaded for the first time and they just have a single copy in the memory. So static block will be executed after the main block is found. Just try removing this main block and you will see the difference yourself
Tricks like putting business code in static initializers (leaving main empty) are possible. But the primary purpose of static initializers is to perform some initializations, not running business code.
You may put something like System.out.println("TestWithoutMain class loaded"); for logging purposes, but this should not be the primary goal of your program.
Java does not prevent you from writing bad, unreadable and unmaintainable code. And from creating nonsense programs. Neither do other programming languages.
Common programming practice discourages you from putting business code in static initializers bypassing main.
Related
So I have already found this question but I'm having a hard time understanding the answers so sorry that this is a repeat question but when should you use a method written in a class vs a method written under the main method. If you're making a method should't you just put it in a class or are there benefits to writing a method under the main method?
public class MyProgram
{
public static void main(String[] args)
{
method();
classMethod.method2();
}
public static void method(){
System.out.println("Method under main method");
}
}
public class classMethod{
public static void method2(){
System.out.println("Method from class");
}
}
Output:
Method under main method
Method from class
They do the same thing is there a time I should use one way over the other?
I'm goin to assume that for under main method you are referring to create the method on the main class or file.
In java like any other language you can make what ever you want using only the main class but that isn't good, is going to create a really big file and is going to be really hard to maintain.
You use classes in all language to make your program more organize and easy to understand.
(If we dive into really complex program create classes, interface, etc has a lot more reasons that just organize the code, but stick with the basic)
When you need to create a class to hold methods?
That depends on you, and how you want to organize your code.
Its you are really new on Java I recommend to read a little bit on OOP, maybe give you some hints on when you have to use a class or not used.
I probably have quite a big misconception, and I've been looking around the internet and still cant find the answer to my question.
So in java OOP, suppose I have 2 classes one called Main.java, the other Something.java, and because each classes both have their own entry point in their main method.
which one should I start the program with (like to call all the
other classes in that program)?
And, if I were to use Main.java class, how do I call the whole things happening in Something.java? Like if that class was made to do its whole thing, with its own method, variables and all, and I'm just calling it all in the Main.java?
It's quite easy to understand theoretically, but in a program, not so much for me for some reason.
Well it's you who have to decide your entrypoint class. If you decide Main to be entry point class your other main method will treated as normal method like other methods. Hence, you can call that in entrypoint class.
Example below:
public class MultipleMain {
public static void main(String[] args) {
System.out.println("Hello World!!!! I must be executing");
AnotherWithMain.main(new String[]{});
}
}
class AnotherWithMain {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
If you call MultipleMain class i.e. java MultipleMain then output would be:
Hello World!!!! I must be executing
Hello World
and if you call AnotherWithMain then Hello World will be printed per above impl.
One program must have one main method to start with. Because if you ran two main method using java Your_Class then you have 2 jvm instance.
look into some tutorial how to use multiple classes in one program .
Using multiple classes in a Java program
Generally your main class will use other classes instance and static method. see the above simple example.
Is it possible to check that class has static block ?
For example to check that class has static fields reflection can be used by calling clazz.getDeclaredFields() and then iterate it to found static field.
With static methods the same - clazz.getDeclaredMethods()
But getDeclaredMethods doesn't return methods for init and clinit. Is there are any other way to check that class have static initialization block?
There is no way to test for the presence of static initializers, as that information isn’t even available at byte code level. In a class file, there might be a single initialization method, <clinit>, whose existence might be caused by the existence of static field initializers, static initialization blocks, or the mere presence of an assert statement somewhere in that class, to name some possible reasons. Of course, there could be more than one reason, including reasons not mentioned here. Since that bytecode artifact has no language semantic, there is no Reflection method to test for its presence.
However, if a class has no mutable static fields, there is nothing to manipulate by a static initializer, that could make a difference between a “fresh class” and a class state that is not “fresh”. While initializers could have side effects, these could not alter the class, if there are no static fields to change. But if the initializer is manipulating the state of other classes, you get initialization order dependency issues anyway.
Also, the idea to reload a single class because of fulfilling certain criteria, without reloading the others, which interact with that class, doesn’t work at all, as these old classes will also stay linked as they are, not using the newly loaded class version.
The simplest (if not only) solution is to reload all classes of a particular class loader, to get a fresh new state. Trying to selectively reload some classes only, is just an optimization attempt, but there is no point in trying to optimize a testing environment…
Use below code.
public static boolean check(Class<?> cls) {
try {
Method method = ObjectStreamClass.class.getDeclaredMethod("hasStaticInitializer", Class.class);
method.setAccessible(true);
return (boolean) method.invoke(null, cls);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
}
// trivial
throw new RuntimeException();
}
static class Test { static { } }
static class Test2 { }
public static void main(String[] args) {
assert check(Test.class);
assert !check(Test2.class);
}
You can not do what you are wanting to do because that is not how things work. Even if you could it is a terrible idea and means you have a fundamental flaw in your design of your system.
Static Initialization Blocks
A static initialization block is a normal block of code enclosed in
braces, { }, and preceded by the static keyword. Here is an example:
static {
// whatever code is needed for initialization goes here
}
A class can have any number of static initialization blocks, and they
can appear anywhere in the class body. The runtime system guarantees
that static initialization blocks are called in the order that they
appear in the source code.
There is an alternative to static blocks — you can write a private
static method:
class Whatever {
public static varType myVar = initializeClassVariable();
private static varType initializeClassVariable() {
// initialization code goes here
}
}
The advantage of private static methods is that they can be reused
later if you need to reinitialize the class variable.
My goal is to have several classes to have a block of code that runs at the beginning of the program. Assume for a second that classes can be added to the project on a whim, and it will be impractical to have a static function that is called in the beginning of main.
I have tried to place the initialisation routine within the static block of those classes, and it works almost as expected, but not quite. These blocks get called only after something else in that class gets called. This can be demonstrated by the code below:
Test.java
public class Test
{
public static void main(String[] args)
{
System.out.println("Begin");
new Another();
}
}
Another.java
public class Another
{
static
{
System.out.println("Another.static{}");
}
public Another()
{
System.out.println("Another.Another()");
}
}
Another2.java
public class Another2
{
static
{
System.out.println("Another2.static{}");
}
public Another2()
{
System.out.println("Another2.Another2()");
}
}
The output is:
Begin
Another.static{}
Another.Another()
It can be seen that Another2 is assumed not to be there at all.
The question is: Is it possible to "kick" all the classes to execute their static blocks if they have them?
Static blocks are executed if the class is loaded by the ClassLoader. So if you iterate over all your classes and load them via a class loader (no need to instantiate them!) every static block would get executed once.
On a deeper level I can't imagine a situation where you'd actually need this. This somehow hints to misdesigned class structures.
This is not possible, since the VM will never attempt to load a class that isn't required by the code path traversed on its own. There are some obvious and some obscure reasons why its done that way.
Rule of thumb is: If there is no dependency to a class that is reachable (through code) from the programs entry point, then that class will never be loaded. Although reachable is quite lose, e.g. a reference can be established by just knowing a class' name (e.g. from a configuration file) and accessing that class with e.g. Class.forName().
What you cannot achieve is just dropping a class into the class path and have that class automagically become an additional entry point (which executing any static code without a cause from the main (and only) entry point would classify as).
Simply you can't. Static block only called when the class loader loads them for the first time into it. No other way around to call them.
It doesn't make sense to load all keep with you to use them later. Anyways, it will be executed when you use it.
This question already has answers here:
What is the difference between a static and a non-static initialization code block
(9 answers)
Closed 8 years ago.
I was looking over some code the other day and I came across:
static {
...
}
Coming from C++, I had no idea why that was there. Its not an error because the code compiled fine. What is this "static" block of code?
It's a static initializer. It's executed when the class is loaded (or initialized, to be precise, but you usually don't notice the difference).
It can be thought of as a "class constructor".
Note that there are also instance initializers, which look the same, except that they don't have the static keyword. Those are run in addition to the code in the constructor when a new instance of the object is created.
It is a static initializer. It's executed when the class is loaded and a good place to put initialization of static variables.
From http://java.sun.com/docs/books/tutorial/java/javaOO/initial.html
A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
If you have a class with a static look-up map it could look like this
class MyClass {
static Map<Double, String> labels;
static {
labels = new HashMap<Double, String>();
labels.put(5.5, "five and a half");
labels.put(7.1, "seven point 1");
}
//...
}
It's useful since the above static field could not have been initialized using labels = .... It needs to call the put-method somehow.
It's a block of code which is executed when the class gets loaded by a classloader. It is meant to do initialization of static members of the class.
It is also possible to write non-static initializers, which look even stranger:
public class Foo {
{
// This code will be executed before every constructor
// but after the call to super()
}
Foo() {
}
}
Static block can be used to show that a program can run without main function also.
//static block
//static block is used to initlize static data member of the clas at the time of clas loading
//static block is exeuted before the main
class B
{
static
{
System.out.println("Welcome to Java");
System.exit(0);
}
}
A static block executes once in the life cycle of any program,
another property of static block is that it executes before the main method.
Static blocks are used for initializaing the code and will be executed when JVM loads the class.Refer to the below link which gives the detailed explanation.
http://www.jusfortechies.com/java/core-java/static-blocks.php
yes, static block is used for initialize the code and it will load at the time JVM start for execution.
static block is used in previous versions of java but in latest version it doesn't work.