In a constructor, find which class created the object? [duplicate] - java

This question already has answers here:
How do I find the caller of a method using stacktrace or reflection?
(13 answers)
Closed 8 years ago.
Here's what I'm trying to do:
In my code, I have sets of classes that create objects of other classes. What I am trying to do is, in the constructor of the class that's constructor gets called, find the class which called the constructor in the first place.
For example:
Main.java:
public class Main {
public static void main(String[] args) {
Test t = new Test();
}
}
Test.java:
public class Test {
public Test(){
//somehow find the class where I came from :(
}
}

Assuming that you can't pass in the Class object of your caller: Other than the fact that the very need for this implies a rather obnoxious design, then, the only way you can do this is to construct an exception and inspecting the last stack trace element in it:
Exception e = new Exception();
StackTraceElement[] elements = e.getStackTrace();
The first element in the array is what you're looking for.
(Updated following a comment) This won't work consistently in JITted environments.

You can use something like this:
public class Main {
public static void main(String[] args) {
new Main().runMe();
}
public void runMe() {
new Test(this.getClass());
}
}
class Test {
public Test(Class clazz) {
System.out.println("I was invoked from '" + clazz.getCanonicalName() + "' class.");
}
}
Prints:
I was invoked from 'Main' class.

Related

What is the flow of the program and Why it's stackOverFlow Error [duplicate]

This question already has answers here:
Why does this Java code create a stack overflow error?
(6 answers)
java StackOverflowError when local and instance objects creation
(4 answers)
Closed 3 years ago.
Why this program gives this exception
"Exception in thread "main" java.lang.StackOverflowError at com.Test.<init>(Test.java:5)"
Code:
public class Test {
Test t = new Test();
public static void main(String[] args) {
Test t = new Test();
}
}
It happens because you initialize an instance level variable as an instance of the class where it is defined itself which results in the endless recursion and the JVM throws the StackOverflowError:
A new instance of Test in the main method creates Test which initializes Test as the instance level variable which creates Test which initializes Test as the instance level variable etc...
To fix it, remove the first line of the code in the class and use the following:
public class Test {
public static void main(String[] args) { // this static method is called once upon
Test t = new Test(); // the start and creates an instance once
}
}
Every class instance calling new class instance (endlessly), and therefore the StackOverflowError
Just remove the unused field from class:
public class Test {
public static void main(String[] args) {
Test t = new Test();
}
}
StackOverFlowError is coming because you are creating same class object as instance level variable. So whenever you create an instance of this class, internally it will create instance of Test class [as you have defined it as instance level variable] and because of this it will again create instance of Test class and so on....
So you will have to remove the instance level object creation as follow :-
public class Test {
public static void main(String[] args) {
Test t = new Test();
}
}

How to pass a parameter to a public static void main class? [duplicate]

This question already has answers here:
Is it possible in Java to Invoke another class' main method and return to the invoking code?
(5 answers)
Closed 3 years ago.
I have a question in passing a parameter to a public static void main class.
Basically I have the following main class here:
public class testClass{
public static void main(String[] args) {
try {
...//code
String clientId = "test" + args0;
...
} catch(Exception e) {
e.printStackTrace();
}
}
Now I want to pass an id as args0 for the clientid. My attempt is to write a step definition like so:
When I enter the clientId "xxxxxx"
Then in my step def actually call on the main method but it's the below I am having trouble with. I know how to pass parameters from one method to another but how do I pass it in a main where we require an args?
#When("^I enter the clientId \"([^\"]*)\"$")
public void ientertheClientId(String clientId) {
testClass.main(clientId);
}
Above gives me a red line for the method
The function ientertheClientId must be static to call the function main.

How is it possible to create object in Class definition itself?

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.

<T> cannot be resolved to a type Java

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
}

how to create an object of a class in a different package in another class [duplicate]

This question already has an answer here:
Import custom Java class
(1 answer)
Closed 9 years ago.
I am a beginner at java, I used to code in C++ and there when using classes I used to define them in separate files and then include those classes in my main file.
I'm trying to learn threads for socket programming so I can open multiple server ports as threads and accept multiple clients. I know that in Java the file name should be the same as the class name (correct me if i am wrong). This is what I am trying to do:
main.java
include derived.java;
class main1
{
main1()
{
System.out.println("Constructor of main1 class.");
}
void main1_method()
{
System.out.println("method of main 1 class");
}
public static void main(String[] args)
{
main1 my = new main1();
Derived derivedThread = new Derived();
derivedThread.start();
}
}
derived.java
public class derived extends Thread
{
public void run()
{
System.out.println("starting a new thread");
}
}
How can I create a derived class object in main and include it in my main1.java file?
I think I do not fully understand how classes work in Java and what classpath has to be used with it. I have a deadline for my networking project and I am very behind so please help me!
Delete your files and try this, this is how it should look in Java:
Derived class: Derived.java
public class Derived extends Thread {
public void run() {
System.out.println("starting a new thread");
}
}
Main1 class: Main1.java
public class Main1 {
public Main1() {
System.out.println("Constructor of main1 class.");
}
void main1_method() {
System.out.println("method of main 1 class");
}
public static void main(String[] args) {
Main1 my = new Main1();
Derived derivedThread = new Derived();
derivedThread.start();
}
}
Note:
1) Class names are always capitalized, and you are right, the filename must be the same. In addition, the constructor and any calls to the constructor must be capitalized.
2) If you put classes in the same package, you don't need to import them. If you have multiple packages, you would import like so: import packageName.className;. No need for .java at the end, strictly the class name. You can also have nested packages, so you might see things like: import java.util.ArrayList;. This would be using ArrayList class, found in the util package, which is in the java package (built in). You shouldn't have to worry much about making nested packages on smaller projects, but that's the concept.
3) Notice I added the public modifier to Main1 and it's constructor. It is good practice to give a modifier to class names and methods, as well as class variables. See this SO Question for information about modifiers. For a beginner, you should mostly only be concerned with public and private.
I hope that helps, and good luck with your Java studies.
No need to use this include derived.java; .Use import if the derived class exist in different package.The class Derived is different while calling and declaring.
class main1 // Class name must start with Uppercase
{
public static void main(String[] args)
{
main1 my = new main1(); // Can be remove
Derived derivedThread = new Derived();
derivedThread.start();
}
}
public class derived extends Thread // Change derived to Derived
--------------------^
{
public void run()
{
System.out.println("starting a new thread");
}
}
I have remove constructor and one method which is not used.

Categories

Resources