I have the following example in which I am trying to call a method othermethod() of class otherClass from inside the run method. I have created an object of this otherClass class as "obj" and using it to call the method . But it is throwing up NullPointerException.
Please let me know why is so.
package isAlive;
class MyClass
{
static int ans=0;
void counter () throws InterruptedException
{
System.out.println("----------------------------");
synchronized (this){
System.out.println("----entering>>>>"+this+" " +this.getClass().getName());
for (int i=0;i<=10;i++)
{System.out.println(Thread.currentThread()+" "+i);
Thread.sleep(3000);}
System.out.println("----exit>>>>"+this.getClass().getName()); }
}
}
public class staticSync extends Thread
{
MyClass obj;
otherClass oth;
int num;
staticSync(int n)
{
num=n;
}
staticSync(MyClass m,int n)
{
obj= m;
num= n;
}
public void run()
{
try {
// obj.counter();
oth.othermethod();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String ... as)
{try{
// MyClass m1= new MyClass();
// MyClass m2= new MyClass();
staticSync s1= new staticSync(20);
System.out.println("s1--"+s1);
//System.out.println("m1="+m1);System.out.println("m2="+m2);
staticSync s2= new staticSync(15);
System.out.println("s2--"+s2);
staticSync s3= new staticSync(15);
staticSync s4= new staticSync(10);//staticSync s5= new staticSync(m1,10);
s1.start();
s2.start();
}
catch (Exception e)
{}
}
}
class otherClass
{
public synchronized void othermethod()
{
System.out.println("---------------inside othermethod-..>"+this.getClass().getName());
}
}
And the output is :
s1--Thread[Thread-0,5,main]
s2--Thread[Thread-1,5,main]
java.lang.NullPointerException
at isAlive.staticSync.run(staticSync.java:67)
java.lang.NullPointerException
at isAlive.staticSync.run(staticSync.java:67)
Even while using the counter() method i am facing the same problem.
The reason why you're getting a null pointer exception is that you are never assigning a value to oth, and therefore it remains being null from when you declared it.
This
otherClass oth;
^ no value is being assigned
Is basically the same as
otherClass oth = null;
Since it is always null, calling a method from the object throws the error.
Related
I have a class constructor and I need to perform a clone. From what I've read the best choice is to use a copy constructor, just like in C++. However, I've got an issue. If my "regular" constructor throws exceptions and such exceptions aren't even possible in a "copy constructor" how to I implement a try-catch if the first statement must be this.
public class X
{
public X() throws MyException
{
}
public X(final X original)
{
try {
this();
} catch (MyException e)
{
}
}
}
Is the only option add throws MyException to copy constructor?
Copy all data to a new instance by constructor could look like this:
public class X
{
// some Fields....
int a, b, c;
public X() { }
public X(final X originalX) throws InvalidArgumentException
{
if(originalX == null) {
throw new InvalidArgumentException("originalX should not be null!");
}
this.a = originalX.getA();
//...
}
// getter-setter....
}
And it´s called like this in main() or where ever else:
// x_1 is filles with Data...
X x_2;
try {
x_2 = new X(x_1);
} catch(InvalidArgumentException ex) {
LOG.reportError(ex.getMessage());
x_2 = new X(); // prevent NullPointer for usage afterwards
}
I am trying to invoke a method using reflection.
The method I am invoking is not static and in the same class I am invoking it from.
A simplified version of my code:
public class Test {
public static void main(String[] args) {
Test instance = new Test();
if (args.length > 0) {
instance.doWork(args[0]);
}
}
private void doWork(String methodName) {
Method method;
try {
method = this.getClass().getMethod(methodName);
method.invoke(this);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
[...]
}
}
private void MethodOne() { ... };
private void MethodTwo() { ... };
[...]
private void MethodTwenty() { ... };
}
What I am getting is a java.lang.NoSuchMethodException: correct.package.and.class.MethodTwo() despite the package / class / method existing.
Can someone tell me what I am doing wrong?
What I am getting is a java.lang.NoSuchMethodException:
correct.package.and.class.MethodTwo()...
you are calling the getMethod() which is not giving back the private method
Assuming that arg[0] has the right name of the method (if not you'll get a java.lang.NoSuchMethodException again), 2 thing must be done here:
you need to use getDeclaredMethod (because MethodOne is private declared)
your need to set the flag for access to it .setAccessible(true) (this will allow you to invoke a method that is declared private)
Example:
Method method;
try {
method = f.getClass().getDeclaredMethod("doThis");
method.setAccessible(true);
method.invoke(f);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
System.err.println("Opala, somethign went wrong here!");
}
The way you are accessing method is correct.
The method access specifier is private. Thus it is throwing error.
Please change the access specifier to public, it will work.
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) {
Test instance = new Test();
if (args.length > 0) {
instance.doWork(args[0]);
}
}
private void doWork(String methodName) {
Method method;
try {
method = this.getClass().getMethod(methodName);
method.invoke(this);
} catch (Exception e) {
}
}
public void MethodOne() { System.out.println("Method 1"); };
public void MethodTwo() { System.out.println("Method 2"); };
public void MethodTwenty() { System.out.println("Method 3"); };
}
If you are trying to access private methods or constructors, you need to change the code.
Thanks,
Thiruppathi S
CLASS TO INVOKE METHODS FROM
public class Computer {
private String brandName;
private int yearManufactured;
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public int getYearManufactured() {
return yearManufactured;
}
public void setYearManufactured(int yearManufactured) {
this.yearManufactured = yearManufactured;
}
}
IMPLEMENTATION CLASS
public class Test {
public static void main(String[] args) throws NoSuchMethodException,
InvocationTargetException, IllegalAccessException{
Class curClass = Computer.class;
Method[] allMethods = curClass.getDeclaredMethods();
Computer myComputer = new Computer();
for(int c = 0; c < allMethods.length; c++){
Class[] parameterTypes = allMethods[c].getParameterTypes();
for(Class parameterType: parameterTypes){
System.out.println(parameterType.getName());
switch(parameterType.getName()){
case "java.lang.String":
allMethods[c].invoke(myComputer, "LENOVO");
break;
case "int":
allMethods[c].invoke(myComputer, 2021);
break;
}
}
}
System.out.println("BRAND NAME :"+myComputer.getBrandName());
System.out.println("YEAR MANUFACTURED: "+myComputer.getYearManufactured());
}
}
I'm having a trouble with Runnable and Thread implementations. I have this abstract class, that can not be modified:
abstract class Ordenador {
...
protected Ordenador(String nombre, int[] array) {
...
}
protected void escribir() {
...
}
protected abstract void ordenar();
}
And this sort algorithm that inherit from the class above and implements the run() method, which call the sorting one.
class Burbuja extends Ordenador implements Runnable {
protected Burbuja(String nombre, int[] array) {
super(nombre, array);
}
protected void ordenar() {
....
}
public void esperar() {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
public void run() {
this.ordenar();
}
}
Finally I have my main class that creates a random array and create a new Burbuja object that sort the array. The problem is that when calling b.join() the array stay the same so de ordenar() method doesn't get called.
class Aplicacion {
public static void main(String[] args) {
...
Burbuja burbuja = new Burbuja("Burbuja", array);
Thread b = new Thread(burbuja);
...
try {
b.join();
s.join();
... more sorting algorithms...
} catch (Exception ex) {
ex.printStackTrace();
System.exit(-1);
}
System.out.println("");
burbuja.escribir();
}
}
I tried modificating some parts of the code but doesn't work neither.
You have to call the start() method on your thread object
https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html
Your Thread b = new Thread(burbuja); is right, but you forget to call the start method, b.start();
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.
I have a function which calls another function in a different class which throws an exception based on the paraameter provided. I want
public class A {
public int f(int p){
{
B obj = new B();
obj.g(p);
}
}
public class B {
public int g(int p)
{
// throws an exception for this value of p
}
}
Is it possible that I can catch the exception in class A itself and handle it ? I can't change the implementation of class B.
Yeah just use a try-catch statement.
public class A {
public int f(int p){
{
B obj = new B();
try {
obj.g(p);
} catch ( /* the exception */ ) {
// handle the exception
}
}
}
public class B {
public int g(int p)
{
// throws an exception for this value of p
}
}