Hello Friends Iam trying to call Setter method from other Setter method but iam getting nullPointerException in that. Is possible to call setter method from other setter.
Here is my bean class:-
public class ApplicationParameterListEntityTo{
private Long statusValueID;
private WidgetFieldValueBean1 parameterListStatusValueID;
public Long getStatusValueID() {
return statusValueID;
}
public void setStatusValueID(Long statusValueID){
this.statusValueID = statusValueID;
this.parameterListStatusValueID.setWidgetFieldValueID(statusValueID);
}
public WidgetFieldValueBean1 getParameterListStatusValueID() {
return parameterListStatusValueID;
}
Is there any problem in this peace of code.
The following line probably is giving you null pointer
this.parameterListStatusValueID.setWidgetFieldValueID(statusValueID);
Because, the WidgetFieldValueBean1 parameterListStatusValueID object is not initialized before you are calling the setWidgetFieldValueId method
You need to do something like
this.parameterListStatusValueID = new WidgetFieldValueBean1 ();//Considering it has a default constructor
this.parameterListStatusValueID.setWidgetFieldValueID(statusValueID);
Take a look at your setStatusValueID method. Since parameterListStatusValueID is never initialized, it is null, and thus every access to it (like this method, e.g., does), will result in a NullPointerExcetpion.
One way to solve this would be to initialize it in the definition:
public class ApplicationParameterListEntityTo {
private Long statusValueID;
private WidgetFieldValueBean1 parameterListStatusValueID = new WidgetFieldValueBean1();
...
You need to init the member variable parameterListStatusValueID, such as:
private WidgetFieldValueBean1 parameterListStatusValueID = new WidgetFieldValueBean1();
Related
This is what I am trying to achieve:
public class cls1{
public cls1(){} //constructor for the sending class
String name = "foo"; //String I wish to access
public String sentName(){ //Method to access the string outside
return name;
}
}
public class cls2{ //Class where I wish to access the name
public String gotName(Object obj){ //Method where I wish to call the cls1 instance
String recvName;
if(obj.getClass()==cls1.class){
recvName = obj.sentName(); //THE PROBLEM
}
return recvName;
}
}
I do understand that the obj won't have the methods and variables of the cls1 till runtime, and thus can't allow for that line to compile. Is there a way to achieve this?
P.S. I also tried to create an instance of cls1 in cls2:
cls1 cls1Inst;
obj=cls1Inst;
cls1Inst.sentName();
But this gives a nullpointer exception, maybe because I am trying to access the methods of cls1 without actually creating an instance of it (I am not very clear about nullpointer, excuse my dumbness).
Any help would be appreciated.
You can't call sentName() on object class object. You need to typecast it to cls1 class first.
public class cls2{ //Class where I wish to access the name
public String gotName(Object obj){ //Method where I wish to call the cls1 instance
String recvName;
if(obj.getClass()==cls1.class){
cls1 cls1Obj = (cla1)obj;
recvName = cls1Obj.sentName(); //THE PROBLEM
}
return recvName;
}
}
Object is the base class of every object. First you have to Typecast in cls1 then cls1 methods will be available.
Change
recvName = obj.sentName();
to
recvName = ((cls1)obj).sentName();
And in this code
cls1 cls1Inst; // here it is uninitilized (null)
obj=cls1Inst; //<------ after this statement cls1Inst will be same and null
cls1Inst.sentName();// thats why it throws null pointer exception
This code will work
cls1 cls1Inst; // here it is uninitilized (null)
cls1Inst = (cls1)obj; // if obj is not null then typecast it. Now it is assigned to cls1Inst
cls1Inst.sentName(); // it will work perfect file
Updated
Or you can change the function Argument type from Object to cls1. This can avoid extra check for checking class type. see code below.
public String gotName(cls1 obj){
return obj.sentName();// No need to check class type. just return name
}
How should properties be exposed?
For example:
class A{
private ObjectProperty<X> objx;
}
class B{
private ObjectProperty<X> objy;
}
We want to bind objy to objx or add a listener to objx from B. Is it fine to just make a getter for objx? or is there a way to make a wrapper function for binding and expose just this function?
The standard pattern is
class A {
private final ObjectProperty<X> objx = new SimpleObjectProperty<>();
public ObjectProperty<X> objxProperty() {
return objx ;
}
public final X getObjx() {
return objxProperty().get();
}
public final void setObjx(X objx) {
objxProperty().set(objx);
}
}
The idea here is that you have an accessor method for the property itself (a "property accessor": objxProperty()) which can be used for binding and registering listeners, but the property also appears as a regular Java Bean as well: i.e. there are standard get and set methods. The general contract is that you should always have x.getObjx() == x.objxProperty().get(), which is enforced by making the Java Bean accessor methods (getObjx() and setObjx) final.
If you want to be able to modify the property internally, but want to only expose a read only property (to which other code could bind) use a ReadOnlyObjectWrapper:
class A {
private final ReadOnlyObjectWrapper<X> objx = new ReadOnlyObjectWrapper<>();
public ReadOnlyObjectProperty<X> objxProperty() {
return objx.getReadOnlyProperty();
}
public final X getObjx() {
return objxProperty().get();
}
}
Also have a look at this powerpoint presentation which, while old, shows a lot of useful idioms such as lazy- and super-lazy- initialization of the property.
The following structure is used extensively in JavaFX:
class A {
// Private inner property
private ObjectProperty<X> objx;
// Public property accessor method
public final ObjectProperty<X> objxProperty() {
if (objx == null)
objx = new SimpleObjectProperty<X>(DEFAULT_VALUE);
return objx;
}
// Public setter method
public final void setObjx(X val) {
objxProperty().set(val);
}
// Public getter method
public final X getObjx() {return objx == null ? DEFAULT_VALUE : objx.get();}
}
What you can see here is called lazy initialization. The trick is that the private inner property is not initialized until it (really) gets requested.
The public property accessor objxProperty() will initialize the private inner property objx. This property accessor method is used to expose the inner property for binding and listening. The private inner property gets the "Property" suffix, which can be considered as a convention in JavaFX.
The public setter method setObjx uses this property accessor method, therefore in case of the request to set the value of this property, the inner property will be initialized.
It is a bit different in case of the public getter getObjx(), as if the inner property is not initialized yet (no direct access request on the property and no set request before), the default value is returned directly without initializing the inner property, further delaying the initialization routine.
You can see this technique for example in case of alignmentProperty of TextField in JavaFX.
If you don't want to complicate things, the "standard pattern" explained by James_D in his answer is really the standard (the method naming is the same as here).
Basicly i want to get the name of the map that is played from the "World.class", in a string on my main mod class...
public abstract class World implements IBlockAccess{
protected WorldInfo worldInfo;
//=====OtherStuff=====
public World(ISaveHandler par1ISaveHandler, String par2Str, WorldSettings par3WorldSettings, WorldProvider par4WorldProvider, Profiler par5Profiler, ILogAgent par6ILogAgent)
{
this.worldInfo.setWorldName(par2Str);
}
//=====OtherStuff=====
}
i created a class in the same package with this one
public class World_Spy extends World{
public World_Spy(ISaveHandler par1iSaveHandler, String par2Str,
WorldProvider par3WorldProvider, WorldSettings par4WorldSettings,
Profiler par5Profiler, ILogAgent par6iLogAgent) {
super(par1iSaveHandler, par2Str, par3WorldProvider, par4WorldSettings,
par5Profiler, par6iLogAgent);
}
#Override
protected IChunkProvider createChunkProvider() {
return null;
}
#Override
public Entity getEntityByID(int i) {
return null;
}
String TheName = "";
public void gotIt(){
TheName = this.worldInfo.getWorldName();
System.out.println(TheName);
}
}
and i call it from my main class with:
World_Spy WName = new World_Spy(null, null, null, null, null, null);
but it chrashes on startup...
any ideas?
World is not a static class... you need an instance of a World compatible object to get the name. One way to get an instance of a World and then the name:
World world = Minecraft.getMinecraft().isIntegratedServerRunning() ? mc.getIntegratedServer().worldServerForDimension(Minecraft.getMinecraft().thePlayer.dimension) : Minecraft.getMinecraft().theWorld;
String worldName = world.getWorldInfo().getWorldName();
This code should work client-side.
You have not initalized worldInfo
protected WorldInfo worldInfo; // initialization MISSING!
So, when you try to instantiate World_Spy which in turn calls its parent class constructor World() you get a NullPointerException at
this.worldInfo.setWorldName(par2Str); // NullPointerException here
To resolve the issue simply provide an instance
protected WorldInfo worldInfo = new WorldInfo();
I believe it "crashes" by throwing NullPointerException here:
this.worldInfo.setWorldName(par2Str);
Indeed variable worldInfo was never initialized by you try to call its method setWorldName(). Since the variable is null at this point throwing NullPointerException sounds reasonable.
In java (exactly like in all other programming languages I know) you have to initialize variable before using it. Indeed primitive types are initialized by default using some kind of "normal" value. However variables of custom types are initialized to null that may confuse beginners.
To initialize you have to use new keyword following by constructor call:
worldInfo = new WorldInfo();
now you can call setters and other methods of worldInfo.
When using an anonymous innerclass inside a method, when we want to use a method parameter inside the anonymous innerclass, we must mark it as final.
Some details here:
Why do we use final keyword with anonymous inner classes?
But what happens when using a class attribute and not a method local attribute?
Simple usecase: a Spring service with a Guava function:
protected LovValueDAO lovValueDAO;
private final Function<String,LovValue> LOV_ID_TO_LOV = new Function<String,LovValue>() {
#Override
public LovValue apply(String input) {
return lovValueDAO.findById(input);
}
};
#Required
public void setLovValueDAO(LovValueDAO lovValueDAO) {
this.lovValueDAO = lovValueDAO;
}
Is it secure to declare such a Guava function?
According to my tests it works fine but what happens behind the hood?
The initialization order is:
Function is initialized
lovValueDAO is injected by spring through the
setter
Thus i guess, as the function is initialized first, that the lovValueDAO attribute used inside the function will not be a copy of the reference but the reference itself since once the DAO is really injected it works fine.
Am i correct?
And what happen if i use this code:
private final Function<String,LovValue> LOV_ID_TO_LOV = new Function<String,LovValue>() {
#Override
public LovValue apply(String input) {
return lovValueDAO = null;
}
};
Will my outside attribute protected LovValueDAO lovValueDAO; be set to null after i call the function?
Inner class holds an implicit reference to this of its enclosing instance (i.e. an instance of its declaring class in context of which it was created), so that access to fields of the declaring class is treated as a normal field access by that reference.
So, your inner class will see the current value of the field, and can change it as well.
Is it possible to set a value for a final attribute from a Private method called from the Constructor of that Object?
public class FinalTest {
private final Object a;
//Constructor
public FinalTest() {
setA();
}
private void setA() {
a = new Object;
}
}
For the above class, compiler gives me an error saying I can't set the value for 'a' from the method.
I understand that its not possible to set value for a final variable from outside a constructor, but in the above case, I am actually doing it in a way within the constructor. So why isn't this allowed?
It's not allowed because you could call setA() via some other non-constructor method later on which would violate the final protection. Since final is a compile time enforced operation, the compiler enforces final by forcing initialization to occur in constructors or in-line.
In your simple example, all looks good but if you later updated your class to something like the following, the problem become more obvious...
public class FinalTest {
private final Object a;
//Constructor
public FinalTest() {
setA();
}
private void setA() {
a = new Object;
}
public void doSomething() {
this.setA(); // not good because a is final
}
}
Just a note: The compiler has to assume the worst case scenario. By declaring an attribute "final", the compiler has to ensure that the attribute cannot be modified outside of the constructor.
In a case where the method is called using reflection (for example), the compiler would never see it, ever. It's a lot easier to prove something is possible than impossible, that is why the compiler works the way it does.
Final checking is done at compile time not at runtime time. In your case compiler can't be sure that setA would not be called from some other method.
Why do you need to set the value of final variable from a private method ?
You may do it in this way :
public class FinalTest {
private final Object a;
{
a=new Object();
}
//Constructor
public FinalTest() {
}
}
In this case the object will be initialized on every FinalTest initialization.