Null pointer exception on getter setter in java - java

I have a getter setter class named SharedData.java . I am getting null pointer exception when I'm going to imply it on my code . Here is the SharedData class :
public class SharedData {
private static SharedData instance = null;
public SharedData() {
// randomizeServers();
}
// data to be shared
private double src_latitude = -1;
private double src_longitude = -1;
private double end_latitude = -1;
private double end_longitude = -1;
//Getter-Setters
public static SharedData getInstance() {
return instance;
}
public static void setInstance(SharedData instance) {
SharedData.instance = instance;
}
public double getSrc_latitude() {
return src_latitude;
}
public void setSrc_latitude(double src_latitude) {
this.src_latitude = src_latitude;
}
public double getSrc_longitude() {
return src_longitude;
}
public void setSrc_longitude(double src_longitude) {
this.src_longitude = src_longitude;
}
public double getEnd_latitude() {
return end_latitude;
}
public void setEnd_latitude(double end_latitude) {
this.end_latitude = end_latitude;
}
public double getEnd_longitude() {
return end_longitude;
}
public void setEnd_longitude(double end_longitude) {
this.end_longitude = end_longitude;
}
}
Here is my code :
SharedData sharedData ;
sharedData = SharedData.getInstance();
sharedData.setSrc_latitude(latitude);
sharedData.setEnd_longitude(longitude);
Can anybody please help me with this ? Thanks .

You never initialized sharedData, so its value is null, calling a method on it got your program to crash.
I think you're trying to use Singleton Pattern. Try the below:
private static SharedData instance = new SharedData(); \\ Initialize here
private SharedData() { // Make it private....
// randomizeServers();
}
// data to be shared
private double src_latitude = -1;
private double src_longitude = -1;
private double end_latitude = -1;
private double end_longitude = -1;
//Getter-Setters
public static SharedData getInstance() {
return instance;
}

SharedData.getInstance();
Returns null. Later you're trying to call a method on it:
sharedData.setSrc_latitude(latitude);
Which is illegal as reference to object is still null.

You don't instanciate the class, so getInstance() returns null.
At the start of your class, replace :
private static SharedData instance = null;
by :
private static SharedData instance = new SharedData() ; // creates a new instance

change private static SharedData instance = null;
to private static SharedData instance = this;
and make your class static
public static class SharedData {
Also , make the getters setters static..

Even using the singleton pattern you should instantiate the object SharedData at least once.
try this
SharedData sharedData = new SharedData();
sharedData = SharedData.getInstance();
sharedData.setSrc_latitude(latitude);
sharedData.setEnd_longitude(longitude);

Related

Do I avoid the risk of privacy leaks, if I set the instance variables to private?

I am working on a Java assignment. My professor wrote: Warning: Be sure to set the attributes of the Class in such a way to avoid the risk of any privacy leaks. I am getting confused with it. My understanding towards privacy leaks is always to use a copy constructor, but how can instance variables get privacy leaked? Is this why we always set instance variables to private?
Here is an Example in DemoClass variables are private which can not be accessed directly. You can only get these variables with getters and setters
public class DemoClass {
// you can not get these variable directly
private String stringValue;
private int integerValue;
public DemoClass(String stringValue, int integerValue) {
this.stringValue = stringValue;
this.integerValue = integerValue;
}
public void setStringValue(String stringValue) {
this.stringValue = stringValue;
}
public void setIntegerValue(int integerValue) {
this.integerValue = integerValue;
}
public String getStringValue() {
return stringValue;
}
public int getIntegerValue() {
return integerValue;
}
}
class Main {
public static void main(String[] args) {
DemoClass demoClass =new DemoClass("My String Value",120);
System.out.println(demoClass.getIntegerValue());
System.out.println(demoClass.getStringValue());
}
}
If this is your main code then the answer would be yes, that's why we set any variable except global variables to private.
class Demo {
private String Var = "100";
void Meth(String str) {
System.out.println(str + Var);
}
}
class Main {
public static void main(String[] args) {
Demo demo1 = new Demo();
demo1.Meth("10 x 10 = ");
System.out.println(demo1.Var);//Error. This variable is set to private so it cannot be accessed.
}
}
The privacy or control of your variables can only be accesed by the superclass/control block of the variable.

Java: Objects that always have the same content?

I want to desrcibe my question with an example:
Base.java:
public class Base {
//NO annotations
public AnyClass anyObj;
public Base(){}
}
DerivedOne .java:
public class DerivedOne extends Base{
#SomeAnnotionsOne
public AnyClass anyObjWithAnnotations;
public DerivedOne (AnyClass anyObj){
this.anyObj = anyObj;
anyObjWithAnnotations = this.anyObj;
}
}
DerivedTwo.java:
public class DerivedTwo extends Base {
//These annoations differ from #SomeAnnotionsOne
#SomeAnnotionsTwo
public AnyClass anyObjWithAnnotations;
public Derived_Two(AnyClass anyObj){
this.anyObj = anyObj;
anyObjWithAnnotations = this.anyObj;
}
}
So i just want anyObjWithAnnotations always be equal to anyObj.
Example main:
public static void main(String[] args){
DerivedOne derivedObj = new DerivedOne(new AnyClass());
derivedObj.anyObj = null;
if(derivedObj.anyObjWithAnnotations == null){
System.out.println("anyObjWithAnnotations : is null");
}
}
Nothing is printed. anyObj is null, anyObjWithAnnotations isn't.
My Question:
Is it possible that anyObj is always the same as anyObjWithAnnotations??
So even if i set one of them to null or create a new instance of AnyClass with new the other variable should have the same new content.
EDIT:
Changed whole example to clarify the problem.
You can use below code, where i am creating object 1 time only and then assign its reference into second object. In this way if a value is changed in one object, in example t1, it will be reflected into t2 as well.
class Test {
private int val;
public Test(int val) {
this.val = val;
}
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
}
public class TestSame {
public static void main(String[] args) {
Test t1 = new Test(10);
Test t2=t1;
System.out.println(t1.getVal());
System.out.println(t2.getVal());
t1.setVal(20);
System.out.println(t1.getVal());
System.out.println(t2.getVal());
}
}
O/P :-
10
10
20
20
You can also check that both t1 and t2 has same hashcode value
System.out.println("t1 hashcode "+ t1.hashCode());
System.out.println("t2 hashcode "+ t2.hashCode());
Looks like you need a singleton.
public class Singleton {
private int val = 0;
public void setVal(int val) {
this.val = val;
}
public static final Singleton INSTANCE = new Singleton();
private Singleton() { }
public static Singleton getInstance() {
return INSTANCE;
}
}
Usage example:
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
s1.setVal(42);
If singleton is too much for your case you can use approach:
Object obj1 = new Object();
final Object obj2 = obj1;
since obj2 is final reference - you will not be able to change(reassign) it. So, obj2 and obj1 will refer the same Object instance. But it is possible to reassign obj1 reference. If you set final both obj1 and obj2 - you'll get exactly what you want.
final Object obj1 = new Object();
final Object obj2 = obj1;

Android, couldn't make static getter setter property work?

I was trying this ...
public class Info {
private static Info ourInstance = new Info();
public static Info getInstance() { return ourInstance; }
private static int currentIndex;
public static void setCurrentIndex(int i) {
Log.d("DEV", "setter!");
currentIndex = i;
// do other work here
}
public static int getCurrentIndex() {
Log.d("DEV", "getter!");
return currentIndex;
}
private Info() {
Log.d("DEV", "class initialized no problem...");
currentIndex = 42; // just doesn't work, only sets the field
}
}
in any other class...
Info.currentIndex = 666; // just doesn't work
It just doesn't work - what could the problem be? Tried everything.
Why do you define the setter/getter if you are going to end up doing this?
Info.currentIndex = 666;
if so, then change currentIndex visibility to public...
or even better, be congruent with the code and do
Info.setCurrentIndex(666);

Not sure about Singleton

If I have a singleton class like:
public class MySingleton(){
private static MySingleton istance;
private int element;
private MySingleton(){element = 10;}
public static MySingleton getIstance() {
if(istance == null)
istance = new Mysingleton();
return istance;
}
public void setElement(int i ){
element = i;
}
public int getElement(){
return element;
}
}
and I want to change element's value by calling
MySingleton.getIstance().setElement(20)
Will it change the element value for the istance? Here's an example:
... main () {
MySingleton.getIstance().setElement(20);
System.out.prinln(MySingleton.getIstance().getElement());
// It displays 10, why ?
I suggest you use an enum as it is simpler and thread safe (but not your getter/setter)
public enum MySingleton() {
INSTANCE;
private int element = 10;
public void setElement(int element) { this.element = element; }
public int getElement() { return element; }
}
MySingleton.INSTANCE.setElement(20);
System.out.prinln(MySingleton.INSTANCE.getElement()); // prints 20.
I'm not sure if your code block above was copied in or just retyped, but there were a few basic compilation issues I saw with it - when you're setting MySingleton in getInstance, you need to check capitalization. Also, your class declaration shouldn't have (parentheses). After fixing these two things and running basic main, I got 20.
This is the same as what you had - no synchronization or anything else, but on a single thread it doesn't seem necessary.
public class MySingleton{
private static MySingleton istance;
private int element;
private MySingleton(){element = 10;}
public static MySingleton getIstance() {
if(istance == null)
istance = new MySingleton();
return istance;
}
public void setElement(int i ){
element = i;
}
public int getElement(){
return element;
}
public static void main(String[] args) {
System.out.println(MySingleton.getIstance().getElement());
MySingleton.getIstance().setElement(20);
System.out.println(MySingleton.getIstance().getElement());
}
}
should have an output of
10
20
Im not sure if your code really work, how azurefrog say, make your code synchronized, and in youre line public static getIstance() { you need to set the return type.

Getting a Java field through reflection, but not from its String name

Is it possible to get a Field through Java reflection if I have the field itself? It's a primitive float (public, no problem). I don't want to use its name as a String.
Example:
public class TVset {
public float voltageA;
public float voltageB;
public float voltageC;
public TVset(...) {...} // constructor
public void function() {...} // it changes voltages
}
class Voltmeter{
Object theObject;
Field theField;
Voltmeter(Object obj) {
theObject = obj;
Class theFieldClass = obj.getClass();
Class theContainerClass = theFieldClass.getDeclaringClass();
Field theField = ??? // <-- here I don't want to use a String
}
float getVoltage() {
return theField.getFloat(theObject);
}
}
TVset tv1 = new TVset(...);
TVset tv2 = new TVset(...);
Voltmeter meter = new Voltmeter(tv1.voltageB);
meter.getVoltage();
tv1.function();
meter.getVoltage(); <- should reflect the changed voltage
tv1.function();
meter.getVoltage(); <- should reflect the changed voltage
...
The effect is similar to passing the float by reference, but without wrapping it into a wrapper class.
I need to measure different voltages on different TV sets, just by changing the line:
Voltmeter meter = new Voltmeter(tv1.voltageB);
to something else, like:
Voltmeter meter = new Voltmeter(tv2.voltageA);
Is it possible to do it with reflection?
Thx
To use reflection you have to use a String. Instead of using a float you can use an object to wrap mutable float or a simple float[1];
BTW I wouldn't use float unless you have a really good reason, double suffers far less rounding error.
public class TVset {
public double[] voltageA = { 0.0 };
public double[] voltageB = { 0.0 };
public double[] voltageC = { 0.0 };
}
class Voltmeter{
final double[] theField;
Voltmeter(double[] theField) {
this.theField = theField;
}
double getVoltage() {
return theField[0];
}
}
// works just fine.
Voltmeter meter = new Voltmeter(tv1.voltageB);
EDIT: Using an abstract accessor. This is the fastest way to do this. AFAIK,the difference is less than 10 nano-seconds.
public abstract class Voltmeter{ // or use an interface
public abstract double get();
public abstract void set(double voltage);
}
public class TVset {
private double _voltageA = 0.0;
private double _voltageB = 0.0;
private double _voltageC = 0.0;
public final Voltmeter voltageA = new Voltmeter() {
public double get() { return _voltageA; }
public void set(double voltage) { _voltageA = voltage; }
}
public final Voltmeter voltageB = new Voltmeter() {
public double get() { return _voltageB; }
public void set(double voltage) { _voltageB = voltage; }
}
public final Voltmeter voltageC = new Voltmeter() {
public double get() { return _voltageC; }
public void set(double voltage) { _voltageC = voltage; }
}
}
Personally, if speed is critical, I would just use the fields directly by name. You won't get simpler or faster than that.
Just for completeness I've included the delegate way of solving this. I would also not recommend having your floats with public access.
public class stackoverflow_5383947 {
public static class Tvset {
public float voltageA;
public float voltageB;
public float voltageC;
public Tvset() {
}
public void function() {
voltageA++;
}
};
public static class Voltmeter {
private VoltageDelegate _delegate;
public Voltmeter(VoltageDelegate delegate) {
_delegate = delegate;
}
float getVoltage() {
return _delegate.getVoltage();
}
};
public static interface VoltageDelegate {
public float getVoltage();
}
public static void main(String[] args) {
final Tvset tv1 = new Tvset();
Voltmeter meter = new Voltmeter(new VoltageDelegate() {
public float getVoltage() {
return tv1.voltageA;
}
});
System.out.println(meter.getVoltage());
tv1.function();
System.out.println(meter.getVoltage());
tv1.function();
System.out.println(meter.getVoltage());
}
}
If you control the TVSet but need to use reflection for some reason, a good way to avoid errors is to write the method/field names that you need as String Constants in the TVSet class.
However if your concern is performance, reflection is not the way to go because accessing a field or method through reflection can be much slower than accessing through getters or directly.
Here a variant where you can give your float value instead of a string.
class Voltmeter{
Object container;
Field theField;
Voltmeter(Object obj, float currentValue) {
container = obj;
Class<?> containerClass = obj.getClass();
Field[] fields = containerClass.getFields();
for(Field f : fields) {
if (f.getType() == float.class &&
f.getFloat(container) == currentValue) {
this.theField = f;
break;
}
}
}
float getVoltage() {
return theField.getFloat(container);
}
}
Then call it like this:
Voltmeter meter = new Voltmeter(tv1, tv1.voltageB);
It works only if the voltages in the moment of Voltmeter creation are different (and not NaN), as it takes the first Field with the right value. And it is not really more efficient, I think.
I wouldn't really recommend this.

Categories