I would like to know, how to call the main method as it is in a JButton into a JFrame with an action performed, i mean, just press Compare Button & execute the code from main class (Main class is separate from JFrame code).
public static void main(String[]args){
Comparative comp = new Comparative();
if(comp.loadComparative(args[0])){
comp.compareDbs();
comp.sendEmail();
}
}
private void CompareActionPerformed(java.awt.event.ActionEvent evt) {
?????????????
}
If the main class is on the classpath you can use reflection :
private void CompareActionPerformed(java.awt.event.ActionEvent evt) {
MyMainClassToCall.main(myArgs);
}
If the class is located elsewhere, likely in a jar, you can certainly use an URLClassLoader to load the class which contains the main method, then use
myMainClass.getMethod("main", String[].class).invoke(null, myArgs);
You can just get the arguments you need and then call it using the name of the class where it is:
MainClass.main(args);
To give a complete answer we actually need to know what's the name of the class that contains that main method. Also, I'm struggling to understand such a weird requirement but I'll do my best to come up with a useful answer.
To invoke your main method you need to access it through the class that contains it, since it's a static method. You also need to provide an array of arguments mainly because it seems that your main method is using the first of the elements in the arguments array. So something like this would work:
private void CompareActionPerformed(java.awt.event.ActionEvent evt) {
String[] args = new String[] { "myparam" };
MainClass.main(args);
}
Now, said that, let me note that such an invocation of a main method is a very bad practice, you could achieve the same copying the contents of your main method into your event handler CompareActionPerformed. Or even better, creating a separate and independent class with an static method that performs the same that you need from your main method. Then invoke that new static method from your main class and from your event handler (assuming that all the code is accessible from the same class loader).
I think it's a bad practice , you should follow some design pattern , like MVC or something , when JVM starts it looks for the "main" method and start from there , the thing you can do before calling main method is putting some code in a static braces like ...
public class test {
static {
some code
}
public static void main(String[] args){
}
}
this code will be executed before the main
There is just one class, it is Comparative inside it's all the code incluing the main....
Related
If I understand the meaning of each keyword correctly, public means the method is accessible by anybody(instances of the class, direct call of the method, etc), while static means that the method can only be accessed inside the class(not even the instances of the class). That said, the public keyword is no use in this situation as the method can only be used inside the class. I wrote a little program to test it out and I got no errors or warnings without putting the public key word in front of the method. Can anyone please explain why public static methods are sometimes use? (e.g. public static void main(String[] args))
Thank you in advance!
Static methods mean you do not need to instantiate the class to call the method, it does't mean you cannot call it from anywhere you want in the application.
Others have already explained the right meaning of static.
Can anyone please explain why public static methods are sometimes use?
Maybe the most famous example is the public static void main method - the standard entry point for java programs.
It is public because it needs to be called from the outside world.
It is static because it won't make sanse to start a program from an object instance.
Another good examle is a utility class, one that only holds static methods for use of other classes. It dosen't need to be instantiated (sometimes it even can't), but rather supply a bounch of "static" routines to perform, routines that does not depend on a state of an object. The output is a direct function of the input (ofcourse, it might also be subject to other global state from outside). this is actually why it is called static.
That said, the static keyword is not always used because you want to have access to some members in a class without instantiating it, but rather because it makes sense. You keep a property that is shared among all instances in one place, instead of holding copies of it in each instance.
That leads to a third common use of public static (or even public static final) - the definition of constants.
A public static method is a method that does not need an instance of the class to run and can be run from anywhere. Typically it is used for some utility function that does not use the member variables of a class and is self contained in its logic.
The code below chooses a path to store an image based on the image file name so that the many images are stored in a tree of small folders.
public static String getImagePathString(String key){
String res = key.substring(3, 4)+File.separator+
key.substring(2, 3)+File.separator+
key.substring(1, 2)+File.separator+
key.substring(0, 1);
return res;
}
It needs no other information (it could do with a safety check on the size of key)
A quick guide to some of the options...
public class Foo {
public static void doo() {
}
private static void dont() {
}
public Foo() {
doo(); // this works
dont(); // this works
Foo.doo(); // this works
Foo.dont(); // this works
this.doo(); // this works but is silly - its just Foo.doo();
this.dont(); // this works but is silly - its just Foo.dont();
}
public static void main(String[] args) {
doo(); // this works
dont(); // this works
Foo.doo(); // this works
Foo.dont(); // this works
Foo foo = new Foo();
foo.doo(); // this works but is silly - its just Foo.doo();
}
}
public class Another {
public static void main(String[] args) {
Foo.doo(); // this works
Foo.dont(); // this DOESN'T work. dont is private
doo(); // this DOESN'T work. where is doo()? I cant find it?
}
}
public class A{
public static void main(String[] args)
{
//Main code
}
}
public class B{
void someMethod()
{
String[] args={};
A.main();
System.out.println("Back to someMethod()");
}
}
Is there any way to do this? I found a method of doing the same using reflection but that doesn't return to the invoking code either. I tried using ProcessBuilder to execute it in a separate process but I guess I was missing out something.
Your code already nearly does it - it's just not passing in the arguments:
String[] args = {};
A.main(args);
The main method is only "special" in terms of it being treated as an entry point. It's otherwise a perfectly normal method which can be called from other code with no problems. Of course you may run into problems if it's written in a way which expects it only to be called as an entry point (e.g. if it uses System.exit) but from a language perspective it's fine.
Yes you can do call A.main().
You can do this:
String[] args = {};
A.main(args);
If you don't care about the arguments, then you can do something like:
public static void main(String ... args)
and call it with:
A.main(); //no args here
There's nothing magic about the name "main". What you've sketched ought to work, so your problem must be something else. Test my claim by changing the name of "main" to something
else, I bet it still doesn't work.
Actually, you can call main method like the way you have just asked but not the way you have done it. First, every execution process starts from the main method. So, if you want to do it the way you want you can do right this way. This code will execute Hello! World eight times:
class B
{
B()
{
while(A.i<8)
{
String a[]={"Main","Checking"};
A.main(a);
}
System.exit(0);
}
}
class A
{
public static int i=0;
public static void main(String args[])
{
System.out.println("Hello! World");
i++;
B ob=new B();
}
}
`
The iteration part, you can leave it if you want.
I Hope I gave you the solution just the way you wanted. :)
Of course.
String[] args = {};
A.main(args);
Just be aware: from purely what you have up there, the main method is still the entry point to the program. Now, if you are trying to run the main method in a new PROCESS, this is a different story.
I have a simple Java theory question. If I write a class that contains a main() method along with some other methods, and within that main method invoke an instance of the class (say new Class()), I'm a bit confused why a recursion doesn't occur. Let's say I'm writing a graphing program, where the other methods in the class create a window and plot data; in the main method I call an instance of the class itself, and yet only one window appears. That's great, and it's what I wanted, but intuition suggests that if I create an instance of a class from within itself, some sort of recursion should occur. What prevents this? Here is an example (in my mind, I'm wondering what prevents unwanted recursion):
public class example{
method1(){create Jpane}
method2(){paint Jpane}
method 3(){do some computations}
public static void main(String[] args){
new example(); // or create Jblah(new example());
}
}
I think you're confusing the main method - which is just the entry point of the program - with a constructor.
For example, if you wrote:
public class Example {
public Example() {
new Example(); // Recursive call
}
public static void main(String[] args) {
// Will call the constructor, which will call itself... but main
// won't get called again.
new Example();
}
}
Then that would go bang.
The main method does not get executed automatically when you instance a class. It simply can be used as an entry point to an application - and then will be executed once.
Recursion isn't a bad thing. I suspect you are asking why there isn't an infinite recursion.
The big concept you are missing is that when you call new Example() you are allocating memory and then invoking just one method (the constructor). The main() is only invoked at the start of the whole program unless you explicitly call it.
--- edited to add
public class MyMainClass {
public static void main(String arg[]) {
Calculator c = new Calculator();
int x = c.factorial(5);
}
}
class Calculator {
Calculator() { }
public int factorial(int x) {
if (x > 1) return x * factorial(x - 1);
else return 1; // WARNING: wrong answer for negative input
}
}
Since factorial doesn't use any instance variable, it could have been declared static and called as Calculator.factoral(5); without even using new, but I din't do that since showing off new was the whole point of the example.
just because you have a main method in the class doesn' mean that it will be called every time you create the class.
Java looks for main as an entry point for the program, and calls it upon startup. Any objects you instantiate from their do not call main, since as far as java is concerned, it has done its job of making the entry point to the program.
Suppose the classes has code like this:
class C {
public static void show() {
}
}
class CTest {
public static void main (String[] args) {
C.show();
}
}
Then will it be perfectly legal to conclude that while referring to class C to access the static method show() here, behind the scene Java is actually calling the show() method through Java reflection ?
I.e. is it actually doing something like this
Class test = Class.forName(C);
test.show();
to call static methods?
If not, then how is it actually calling the static methods without creating objects?
If the above explanation is true, then how we'll justify the statement that "static members are only associated with classes, not objects" when we're actually invoking the method through a java.lang.Class object?
The JVM doesn't need to do anything like Class.forName() when calling a static method, because when the class that is calling the method is initialized (or when the method runs the first time, depending on where the static method call is), those other classes are looked up and a reference to the static method code is installed into the pool of data associated with that calling class. But at some point during that initialization, yes, the equivalent of Class.forName() is performed to find the other class.
This is a specious semantic argument. You could just as easily say that this reinforces the standard line that a static method is associated with the class rather than any instance of the class.
The JVM divides the memory it can use into different parts: one part where classes are stored, and one for the objects. (I think there might have been third part, but I am not quite sure about that right now).
Anyways, when an object is created, java looks up the corresponding class (like a blueprint) and creates a copy of it -> voila, we have an object. When a static method is called, the method of the class in the first part of the memory is executed, and not that of an object in the second part. (so there is no need to instantiate an object).
Besides, reflection needs a lot of resources, so using it to call static methods would considerably impact performance.
For extra info:
The called class will get loaded when it's first referenced by calling code.
i.e. The JVM only resolves and loads the class at the specific line of code that it first needs it.
You can verify this by using the JVM arg "-verbose:class" and stepping through with a debugger.
It will call ClassLoader.loadClass(String name) to load the class.
You can put a println statement into the ctor, to verify, whether it is called or not:
class C {
public static void show () {
System.out.println ("static: C.show ();");
}
public C () {
System.out.println ("C.ctor ();");
}
public void view () {
System.out.println ("c.view ();");
}
}
public class CTest
{
public static void main (String args[])
{
System.out.println ("static: ");
C.show ();
System.out.println ("object: ");
C c = new C ();
c.view ();
c.show (); // bad style, should be avoided
}
}
I have two java classes.One in which my GUI is written and the other class in which i have implemented an interface(call it class 2).My project starts from the main method of GUI.I want to send a string to my GUI class from the class 2 for displaying it in the Text area but nothing is happening.
As my main gui class is
public class GraphicalInterface extends javax.swing.JFrame{
//I have created a function over here for displaying string in text area
public void show1(String name)
{
jTextArea1.setText(name);
}
//buttons code
public static void main(String args[]) {
//code
}
}
I have created an object of this class in my class 2 like below
GraphicalInterface b=new GraphicalInterface();
b.show1("pear");// it does not allow me to write this statement
Please help me out that how can i call main method class from another java class.Thanks.
You may be trying to call this code outside of a constructor or method (or initializer block) and in Java, this can't be done. Instead call this code inside of a method or constructor.
I guess that you have a design problem in your project. Let me expain. You say you have a GUI class "GraphicalInterface" which holds the main method which is the starting point of an application in Java. You say you need to call the main method of this class in another class,
"your class 2". If so why isn't the place belonging to the "main method" of your application in which you try to call this GUI's main method. Call GUI's main method x(), let the place that you call x() belong to the main method.
If you need to operate on the GUI's fields in another classes and also keep the main method still there, then I suggest you to apply Singleton Pattern to your GUI class. In that way you
will be able to refer the only instance of your public singleton class everywhere in your application.
public class GraphicalInterface extends javax.swing.JFrame
{
public String textAreaContent;
public getX()( return textAreaContent;)
public setX(String s)( this.textAreaContent = s;)
public void show1()
{
jTextArea1.setText(this.getTextAreaContent());
}
public static void main(String args[])
{
//code
}
}
From your other class:
GraphicalInterface b=new GraphicalInterface();
b.setX("text area content");
b.show1();
No, the best solution is not to do this, and if you feel you must, it is likely because your design is somehow broken. Instead write your code so that your classes are true OOPs classes that interact in an intelligent way (low coupling, high cohesion), and to only need one main method.
Also, you state:
GraphicalInterface b=new GraphicalInterface();
b.show1("pear");// it does not allow me to write this statement
What do you mean by "it does not allow me to write this statement"? Does the Java compiler give a compilation error? Does the JVM throw an exception? Does the JVM reach out of your monitor and slap you in the face? Please let us know all the details necessary to be able to help you.
You need to create a method in class2 and call it from your main method.
Sample code class1
public class Test1 {
public void show(String ab){
System.out.println(ab);
}
public static void main(String[] args) {
Test2.Test2();
}
}
Above code i create a class Test1.java like your class1 and create a method with one parameter and call it from class2 method.
Sample code class2
public class Test2 {
static void Test2(){
new Test1().show("Pass String to class1 show method");
}
}
here you can pass your string value.