I recently wrote a class that implements the run method and then parses a video file while grabbing meaningful information. Now I've created a new class that performs a similar operation on the same file but uses a different method of parsing while grabbing other meaningful information. Long story short, I'm required to use two different methods of parsing because some data cannot be extracted by one and some cannot be extracted by the other. The problem I'm facing is that both classes implement the run method, but now I need to start the new class, grab information, start the other class, grab information, then compare the information and print it to the console. This is the gist of what I'm trying to do:
public class first {
[public member variables]
....
public void run(String[] args) {
// parse the file from args and store data
}
public static void main(String[] args) {
new first().run(args); // <------ A
}
}
public class second {
[public member variables]
....
public void run(String[] args) {
// parse the file from args and store data
}
public static void main(String[] args) {
new second().run(args);
}
}
What I'm trying to do is call the first class's main method in order to keep a reference to the class and grab the data from it when it's finished. So I added something like this in the second class:
public class second {
[public member variables]
first firstClass;
int dataFromFirst = 0;
....
public void run(String[] args) {
// parse the file from args and store data
firstClass = new first();
firstClass.main(args); // <------ B
dataFromFirst = firstClass.getSomeData(); // <------ C
}
public static void main(String[] args) {
new second().run(args);
}
}
When I start the second class, everything runs fine, the parser does it's job with both the second and first classes, but when I try to extract the data found by the first class, it's null. I figure once the first class's main method finishes after 'B', once 'A' goes out of scope, everything from the first class is lost. So when I try to get data at 'C', there's nothing there. If this is the case, is there any way I can access the first class's data before it's lost?
I don't have as much knowledge about multithreaded programs so this may just be a very simple solution that I've never seen before.
The reason this doesn't work is that each main method creates its own instance of the class and uses it locally. This has nothing to do with threads, and in fact as far as I can tell your program doesn't actually use multithreading at all.
To fix it, don't call from one main method to the other. In fact, don't even have two main methods in the first place, there's almost never a reason to have more than one. Instead, simply call run directly, like this:
public void run(String[] args) {
// parse the file from args and store data
firstClass = new first();
firstClass.run(args);
dataFromFirst = firstClass.getSomeData();
}
Related
public class example
{
public void method()
{
System.out.println("Shouldn't be here!");
}
}
public class examplemain
{
public static void main(String[] args)
{
example obj = new example();
obj.method();
System.out.println("Inside Main");
}
}
I want to test main only and do not want to call method function.
I used this-
class examplemainTest
{
#Test
void main()
{
example obj = mock(example.class);
doNothing().when(obj).method();
String[] args = new String[0];
examplemain.main(args); //line 1
obj.method(); //line 2
}
}
But still it is calling method function in line 1 and it is only working for line 2.
Following is the output I got after running the test.
Shouldn't be here!
Inside Main
Process finished with exit code 0
The obj variable in examplemain.main() and examplemainTest.main() refer to different objects. In examplemain.main() you call method on the concrete object that you created on the previous line. In examplemainTest.main() you call the method on the mocked object you created in the beginning of the method.
You seem have trouble understanding some of the most fundamental concepts in Java programming. You should spend more time studying object initialization, object references, static access, field visibility and scope before diving into the fairly advanced topic of mocking dependencies in unit tests.
I researched a little bit, best way to handle testing of such kind of classes is provided here
I have some doubt on how this works, consider a simple Java program:
package com.example;
public class Test {
public static void main(String[] args) {
Test t = new Test(); (1) <---- How is this possible
t.print();
}
public void print() {
System.out.println("This is demo");
}
}
This is pretty straightforward program.
However, I have doubt at (1). We are creating an instance of Test, but this is still in the definition of Class Test. How is this possible?
Any explanation to help this would be great.
The instance will be created at run-time.
By then, compile-time is over and all of the code of your application (including all class definition) will be "ready".
Even if you call a constructor of a class that has not been encountered by the JVM up to that point, it will dynamically load the class (in its entirety) before executing the constructor call. Note that a) this might actually fail at run-time, in which case you get a ClassNotFoundError, and b) that cannot happen in your case, because you are calling the constructor of the class from itself (so it must have been loaded already).
The compiler does not run any of your code (not even things like static initializers) during compilation.
But it does make sure (during compilation) that every method or constructor that you are trying to call does in fact exist. Again, this could theoretically fail at runtime (if you mess up class files), in which case you would get a NoSuchMethodError.
First We have to Compile this Porgram using javac After Compilation It will give a Class File.
Now time to Execute Your Class Using java which Invokes JVM and load the Class File to the Class Loader.
java fileName.Class
And here
public static void main(String[] args) {
Test t = new Test(); (1) <---- How is this possible
t.print();
}
All we know static Content (either it is Variable or Method In Java) Of class loaded when ClassLoader loads a Class
As You see Main Method is a static Method. and So, It will Automatically Load into the ClassLoader with class File.
Now JVM First find the public static void main(String... args) in class. Which is a static Content means Its a part of Class but not a part of Class Instance. There is no need of Class Instance to Invoke this MainMethod`.
main(String... args) will be Invoked without getting Instance of the Class. In that Main Method , Your Class is Getting Instantiated
Test t = new Test(); \\here t is reference Variable to Test Class Object.
Now Because Class is loaded into the class Loader new Test(); will create a New Object in Heap memory Area of JVM and your method
public void print() {
System.out.println("This is demo");
}
will be invoked using t.print() Which is a Instance Method (Not Static), So It needs Class Instance to Invoke print() Method.
Q: Test t = new Test(); (1) <---- How is this possible
A: Because of the "static" in public static void main(String[] args)
The "static" means that method "main()" is independent of any specific class object.
You can create any class object you want - including a new "Test" object.
One of the benefits of defining "main" to be static is that you can use "main()" as a test method for the class. Each class can have it's own "main", and you can test each class individually by specifying that class in your Java command line.
For example:
public class MyClass {
public int add2(int n) {
return n + 2;
}
public static void main (String[] args) {
MyClass unitTest = new MyClass ();
System.out.println ("add2(2)=" + unitTest.add2(2));
System.out.println("Expected result=4");
}
}
Then test as follows:
javac MyClass.java
java MyClass
add2(2)=4
Expected result=4
This question has actually been asked and answered many times. For example:
Why is the Java main method static?
==================================================================
Here are a few more examples that illustrate the point:
public class CreateMyself {
private int value = 0;
private static CreateMyself m_singleton = null;
// EXAMPLE 1: You can legally create an instance in the constructor ...
public CreateMyself () {
value++;
// CreateMyself o = new CreateMyself (); // BAD!!! This will cause infinite recursion and crash your stack!!!
System.out.println ("Leaving constructor, value=" + value + "...");
}
// EXAMPLE 2: You can legally create another instance in a normal class member
public void createAnother() {
// But ... WHY??? Is there anything you can't do directly, in your own instance?
CreateMyself newInstance = new CreateMyself ();
System.out.println ("Leaving createAnother, value=" + value + "...");
}
// EXAMPLE 3: This is a common idiom for creating a "singleton"
// NOTE: for this to work, you'd also make the constructor PRIVATE (or protected), so the client *must* call "getInstance()", instead of "new".
public static CreateMyself getInstance () {
if (m_singleton == null) {
m_singleton = new CreateMyself ();
}
System.out.println ("returning singleton instance...");
return m_singleton;
}
// EXAMPLE 4: Creating an instance in "static main()" is a common idiom
public static void main (String[] args) {
CreateMyself newInstance = new CreateMyself ();
newInstance.createAnother ();
}
}
There are many other possible uses. For example, maybe you'll have a static method that does a database lookup and returns a list matching objects.
Note that most of the cases where it's really useful for a class to have a method where it creates an instance of itself are probably static methods.
Why does the following code print "YO"? Whose printYo() is being called? I would think that this code would not compile because printYo() is private to t.
public class Test {
private void printYo() {
System.out.println("YO");
}
public void doubleTrouble(Test t) {
t.printYo();
}
public static void main(String[] args) {
Test test = new Test();
test.doubleTrouble(new Test());
}
}
What can I do to make sure the outer object doesn't mutate the argument class?
printYo() is private to t
No. That method is private in regards to the class Test. Any piece of code within Test can use it.
What can I do to make sure the outer object doesn't mutate the argument class?
Java does not have any built in mechanism to refuse access to members on a per instance basis. (If that is what you meant.)
You are calling the method with in the class , which sound correct for the output . Even if you call the main method from different class it gives the same output.
I've got three classes:
One class which handles my main game operations. Its name is 'PlatformerGame'.
Note: Removed all game-related stuff.
public class PlatformerGame {
public PlatformerGame()
{
}
}
Then, I've got a class called 'PlatformerSingleton' which is meant to provide exactly one instance of the PlatformerGame.
public class PlatformerSingleton {
private static PlatformerGame game;
protected PlatformerSingleton()
{}
public static PlatformerGame getGame()
{
if (game == null)
game = new PlatformerGame();
return game;
}
}
And lastly, I've got the entry point of my application which is supposed to do nothing but get the instance of PlatformerGame and call its 'start' method.
public class Entry {
public static void main(String[] args) {
new PlatformerSingleton.getGame().start();
}
}
However, this is where the error happens:
What does this error mean and how can I prevent it? Also, are there any better approaches to implement this?
Note: I require access to the singleton instance from multiple classes, therefore I need this singleton class.
Don't add new in the line new PlatformerSingleton.getGame().start();
just change your line to:
PlatformerSingleton.getGame().start();
you are not creating new object here, you are just calling the static method of PlatformerSingleton class in which the object of the class is created using Singleton Design Pattern
Remove the new in that call:
new PlatformerSingleton.getGame().start();
Currently, it looks like you're trying to instantiate a class called PlatformerSingleton.getGame (a static nested class called getGame inside PlatformerSingleton).
You're looking for the static method inside PlatformerSingleton. Since it's static, you don't want to instantiate using new at all.
The compiler sees that the syntax is correct, but it doesn't find such class and thus throws an error. These kinds of errors are a bit tougher to correctly debug (as the actual error is syntactical), so you need to look a bit farther to fix it.
Just remove the newkeyword (you don't need new because you're creating PlatformerGameinstance inside of the getGame method):
public static void main(String[] args) {
PlatformerSingleton.getGame().start();
}
Since getGame() is a static method, you do not need to use the new keyword to call the method.
public static void main(String[] args) {
PlatformerSingleton.getGame().start(); // new keyword is not required
}
If getGame() was not static, only then it would have required an instance of PlatformerSingleton class for it to be called and that would have looked like
public static void main(String[] args) {
new PlatformerSingleton().getGame().start(); // if getGame() was a non-static method
}
I'm sorry for the title but I can't really find another way to express it. I need to create a class with a double function, if you give to it a file as input from the console or terminal it gives back a print of it's calculations, but the class can be also used as subroutine and give a file to another class for further calculation.
To implement the first task I must define a main to accept input from console like this
java MyClass myfile.file
But then I can not simply get an instance the class inside something else like this
MyClass myClass = new MyClass(file);
cause I will always get an error from the main(IndexOutOfBound since args it's just an empty array).
How can I fix this? I must use the same class to do so, I can not build another class for the subroutine function.
Something like:
public class MyClass {
public MyClass(String nameOfFile) {
...
}
public void doSomething() {
}
public static void main(String[] args) {
MyClass myClass = new MyClass(args[0]);
myClass.doSomething();
}
}
So your main method simply interprets the incoming arguments (as file names or similar), then instantiates and executes your class as another library might.