I am novice to Java coding.
I wanted to know how to pass the same object between different methods?
Ex:
Class A
{
//Declaring an object say
Object obj;
public void Method1()
{
//Here i want to use some method of obj
obj=new Object();
obj.Metod1();
}
public void Method2()
{
//Here i want to use another method of obj
obj.Metod2();
}
}
class B
{
A aObj=new A();
aObj.Method1();
aObj.Method2();
}
From the above code, how can i use the object created in Method1() can be used in Method2?
This is my actual code:
public class UtilityFunctions
{
File fileName;
public static FileWriter fwObj;
public static BufferedWriter bwObj;
Logger App_log;
UtilityFunctions()
{
fileName=new File(System.getProperty("user.dir")+"\\src\\TempFile.html");
Logger App_log=Logger.getLogger(UtilityFunctions.class);
try
{
if(!fileName.exists())
fileName.createNewFile();
this.fwObj=new FileWriter(fileName);
this.bwObj=new BufferedWriter(fwObj);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void writeHeader()
{
try
{
this.bwObj.append("<html><body><table border='1' style='widht:300px'><tbody><tr><th>Date</th><th>Position</th><th>Site</th></tr>");
this.bwObj.flush();
// this.bwObj.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void writeFooter()
{
try
{
this.bwObj.append("</html></body></table></tbody>");
this.bwObj.flush();
bwObj.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void writeReport(String strstrPositionName)
{
DateFormat format=new SimpleDateFormat("MM/dd/yyyy");
Date date=new Date();
String strCurrentDate=format.format(date);
try
{
String strFormattedString="<tr><td>"+strCurrentDate+"</td><td>"+strstrPositionName+"</td><td>SomeSite</td></tr>";
App_log.info("Printing the Line as: "+strFormattedString);
this.bwObj.append(strFormattedString);
this.bwObj.flush();
// bwObj.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
I would like to call above methods like
Class TempClass
{
public static void main(String args[] args)
{
UtilityFunctions obj=new UtilityFunctions();
obj.writeHeader();
obj.writeReport("Message1");
obj.writeReport("Message2");
// I may add many write Report statements here.
obj.writeFooter();
}
}
The problem i see here, writeHeader is working fine, but at execution of writeReport I am getting NullPointer Exception. How to overcome this?
java.lang.NullPointerException
at UtilityFunctions.writeReport(UtilityFunctions.java:71)
at TempClass.writeDetailedReport etc.........
Here is how you can pass the object frome one method to another
public void method1()
{
Object objToBePassed=new Object();
method2(objToBePassed);
}
public void method2(Object passedObject)
{
// your logic
}
You should create your objects within constructor of the class, and then you can easly use this object. for example:
class YourClass {
private Object obj;
public YourClass() { //constructor
obj = new Object();
}
public void method() {
//your logic
}
To sum up, If you create fields of your class in constructor you don't worry about null pointers and all of class methods have access to those objects. If you want to use private field outside your class, for example in method from other class you should use getter method and pass object in argument:
public void otherMethod(Object obj)
First declare your object as a field for your class:
class MyClass
{
private Object obj;
//...Rest of class goes here
}
Initialize the object in your constructor so that it is not null when you want to access it.
public MyClass()
{
this.obj = new Object();
}
Now you can access it from your two methods as you wish.
public method1()
{
this.obj.doSomething();
}
public method2()
{
this.obj.doSomethingElse();
}
All in all, it can look something like this:
class MyClass
{
private Object obj;
public MyClass()
{
this.obj = new Object();
}
public method1()
{
this.obj.doSomething();
}
public method2()
{
this.obj.doSomethingElse();
}
}
Now if you want to actually pass an object from one method to another but don't want it to be accessible to any other methods, you can make it a parameter like this:
public method1(Object obj)
{
obj.doSomething()
}
And then you can call the method from somewhere else passing specific instances of the object type.
public method2()
{
Object obj1 = new Object();
Object obj2 = new Object();
this.method1(obj1); //All actions in method1 will be done to obj1
this.method1(obj2); //All actions in method1 will be done to obj2
}
Passing parameters is especially useful if you want to call a single method several times, but have it act on different inputs.
Related
How can I pass an anonymous Object to a method (in an other class) and read the data like in the non-working example below?
public static void caller() {
Object obj = new Object() { final String name = "Aloha from Hawaii"; };
consumer(obj);
}
public static void consumer(Object obj) {
System.out.println(obj.name);
}
Regarding to the link provided by jdabtieu:
public static void consumer(Object obj) {
try {
System.out.println(obj.getClass().getDeclaredField("name").get(obj));
} catch (NoSuchFieldException | IllegalAccessException ignored) {
}
}
Is it really that complicated?
However, it's working - and if there is no better solution I'll stay with it.
Many thanks
Let's say I have a class that instantiates and uses another class. From the second class, is it possible to gain access to the first one?
For example:
public class A {
public B obj = new B();
public void something() {
b.somethingElse();
}
}
public class B {
public void somethingElse() {
A owner = getCallingObject();
//the object of class A that called b.somethingElse() is now stored in owner
}
public Object getCallingObject() {
// ?????
// returns the A that instantiated/owns this B
}
}
I know how to get the Class of that object using something like this:
private String getCallerClassName() {
StackTraceElement[] stElements = Thread.currentThread().getStackTrace();
for (int i = 1; i < stElements.length; i++) {
StackTraceElement ste = stElements[i];
if (!ste.getClassName().equals(B.class.getName()) && ste.getClassName().indexOf("java.lang.Thread") != 0)
return ste.getClassName();
}
return null;
}
which I got from a different question: How to get the caller class in Java.
Is there a way to get a pointer to the caller object?
If you control the source code, and if B can only be created by an A object, you could make B a non-static inner class, and then you would automatically get a reference back to the creator of the class, through the A.this pointer. Note this isn't the caller of B::somethingElse(), but the creator of B, which may or may not be the same thing, depending on your use case.
public class A {
public B obj = new B();
public void something() {
obj.somethingElse();
}
void thereAndBackAgain() {
}
public class B {
public void somethingElse() {
A owner = A.this;
owner.thereAndBackAgain();
}
}
}
I have a requirement where in i need to invoke method from class in a particular pattern which is obtained as input argument.
public RandomMethod(String ClassName){
//Eg For Class Name Abc , there is a method AbcProcessor which i need to invoke
ClassName.ClassNameProcessor
}
Since i am getting the argument as String , i am not able to figure out how to cast String into a form where i can call something like Abc.AbcProcessor()
I believe there is some way to do this using reflections. But i am not sure how to proceed.
By reflection you can do that, try following sample:
Class A:
public class A {
public void print(){
System.out.println("A");
}
}
Class B:
public class B {
public void print(){
System.out.println("B");
}
}
Invoking print() from A and B:
public class Test {
public static void callPrint(String className){
try {
Class clazz = Class.forName(className);
Object obj = clazz.newInstance();
clazz.getDeclaredMethod("print").invoke(obj);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
callPrint("test.A");
callPrint("test.B");
}
}
You need to use reflecton, indeed:
public void randomMethod(String fullyQualifiedClassName, String methodName) throws ReflectiveOperationException {
Class<?> clazz = Class.forName(fullyQualifiedClassName);
clazz.getMethod(methodName).invoke(null);
}
which would work assuming you are calling public static method with no arguments
I want to create an object using a method but I want it (object+reference) to live even after the method ends. Example of code:
public class start{
public static void main (String [] Args){
public void createObject(){
object1 createdObject = new object1();
}
createObject();
createdObject.doSomething();
}
}
public class object1{
//code for object 1
}
So my main question is: how to create object using method and let it live even after method ends. The problem is that reference createdObject is popped of stack after method ends and therefore I can't use it anymore. Is it even possible to create object for further use this way?
public class start{
public static void main (String [] Args){
//class level scope
object1 createdObject = null;
private void createObject(){
createdObject = new object1();
}
}
public class object1{
//code for object 1
}
NOTE: I have not following naming conventions. But please follow them in actual code
UPDATE: Proper code check it out
public class Main {
public static void main(String[] args) {
new MyClass().doSomething();
}
}
class MyClass{
Object obj ;
public void doSomething(){
createObject();
}
private void createObject(){
obj = new Object();
System.out.println("Created MyClass instance");
}
}
Your method should return object1 instead of void and you have to add the following line at the end of the method:
return createdObject;
I have a primary class as below:
public class classB{
public classC getObject(String getstring){
return new classC(getstring);
}
}
The classC has a contructor:
public class classC{
String string;
public classC(String s){
this.string = s;
}
public methodC(int i){
<using the `string` variable here>
}
}
Now I've a classA which will be using the object created in classB(which is of course, an instance of classC).
public classA{
int a = 0.5;
<Get the object that was created in classB>.methodC(a);
}
This is needed as a variable is created on some actions from the user and stored in classB and this would be further used in classC's methods. Creating a new object will render my variable in classB set to null which isn't intended.
How can I achieve this?
Assume the Brand is a lightweight objects and Run is heavyweight then creating a field with the container for the lightweight objects and hiding it is a good idea.
But the Brand needs access the container it belongs to it could be done with the mapping but we are simply inject the Run to the Brand so it's better implement the Runable or annotate it with JSR330. And accessing the container through the Run in the normal way.
class MainClass {
public static void main(String[] args) {
Run r = new Run();
}
}
class Run {
private Container con1 = new Container();
public Run() {
Brand cola = new Brand("Coca Cola");
Brand pepsi = new Brand("Pepsi");
// Creates the container object "con1" and adds brands to container.
add(cola);
add(pepsi);
}
public void add(Brand b){
con1.addToList(b);
b.setRun(this);
}
public Container getContainer() {
return con1;
}
}
class Brand {
// In this class I have a method which needs to accsess the con1 object
// containing all the brands and I need to access the method
private String name;
private Run run;
public Brand(String name){
this.name = name;
}
public void brandMethod() {
if(getRun().getContainer().methodExample()) { // Error here. Can't find "con1".**
System.out.println("Method example returned true.");
}
}
public Run getRun() {
return run;
}
public void setRun(Run run) {
this.run = run;
}
}
class Container {
// This class is a container-list containing all brands brands
private ArrayList<Object> list = new ArrayList<Object>();
public boolean methodExample(){
return false;
}
public void addToList(Object o) {
list.add(o);
}
}
If you want to get the object created in classB a static field should do the job
public class classB {
public static objectCReference;
public classC getObject(String getstring){
objectCReference = new classC(getstring);
return objectCReference;
}
}
Then you can access the reference in A
public classA {
int a = 0.5;
if (classB.objectCReference != null) { // Make sure to null check
classB.objectCReference.methodC(a);
}
}
Also please follow the language conventions and start your class names with capital letters.