array as instance variable passed as parameter - java

I have a class with an array as an instance variable/field, which is passed through from another class to the first method in this one.
I was under the impression that I should also be able to access it from another method without also passing it to that method but when I try, I get an NPE.
Here's the code:
public class PLoop {
// instance variable
public Memory[] memList;
// method 1
public void memPass(Memory[] memLocList) {
memList = memLocList;
System.out.println(memList.length);
}
// method 2
public void accessArray() {
System.out.println(memList.length);
}
}
When the first method is called I get an integer printed to the console representing the length of the array but when the second method is called it's NPE, suggesting not the same array.
The second method is called by clicking a button on a GUI. The method associated with this button only has a call along the lines of:
PLoop.accessArray();
Can anyone tell from this what I'm doing wrong?
-EDIT-
The calls to these methods come from two different classes, each of which declares an instance of PLoop:
proc = new PLoop();

I strongly suspect that the instance you've called memPass on isn't the same instance you're later calling accessArray on.
It should be absolutely fine if you're using the same instance. (In particular, it's the value of the argument which will be stored, so it's not like memList can become null after not being null, just due to changes elsewhere.)

The code in the class you have shown looks fine, so if you are getting a NPEx then either the methods are being called out of sequence, or the second method call is being made on a different instance of PLoop to the first.
To check if the calls are being made on the same object or not, try printing out the value of this inside your methods and check if the values are the same:
System.out.println(this);

The Methods in your PLoop classes are not static
Still you are calling PLoop.accessArray();
Can u please tell what is the real Scenario?
Just like #Jon Skeet told the code seems to be fine.The only possibility is that you may be
executing them out of sequence or you may be messing up with memLocList after the first
method is called.

Related

Unable to send instance variable value to a sendkeys() method

Now I have a String variable declared as an instance variable, I'm defining the value to the variable inside a method, but when I try to use the value of the same variable inside another method I get this error:
Keys to send should be a not null CharSequence
Now I cannot event set the return type of first method as String because that method accepts an argument hence that is of no use.
This is my code:
String data;
#Keyword
def getFirstRecord(TestObject listData)
{
List<WebElement> firstRecord = WebUiCommonHelper.findWebElements(listData, 20);
data = firstRecord.get(0).getText();
}
#Keyword
def setSearchData(TestObject obj)
{
WebElement txtSearchBox = WebUiCommonHelper.findWebElement(obj, 20);
txtSearchBox.sendKeys(data);
}
I dont have the reputation to comment so Answering here with possibilities.
Please check below cases for your code to see if these things resolve the issue
Case 1) As mentioned by Nandan A in the comments, check if the method 2 is getting called before method 1.
--> If this is the case then please check your configuraiton for test cases and see why this is happening.
Case 2) If the method 2 is getting called after method 1 as expected by your code.
--> Then as per your coment replied I can see in method 2 the String value is still null. And hence it is possible that this framework is creating new instance of your class for executing your #Keyword implementations everytime. You can solve this in few different ways.
One easiest way to try is make your String variable as static. This way, the value will remain same for all instances, as the static variables are stored on the class level instead of instance level in Java.
Another one can be : from first method write the value in to a properties file, and from the second method read the same properties file and the same key's value.
Let me know if this helps you.

Mockito when and thenReturn statement not working for 2 method calls in Java

Inside my Test class, I have the following mocking statement:
when(metadata.getGranularity(message)).thenReturn(new Assembly.Partition.Builder.build());
Basically, I am calling this above statement through two different test methods. One is existing and works fine, second is my newly written code which calls the same method. It's mentioned inside the setup method. It gets executed in both the cases and when I evaluate the value, it gives an object reference in both the cases, like this:
result= {Assembly$Partition#3793}
The code in my class that it is mocking is:
Assembly.Partition granularity = metadata.getGranularity(message);
But when the debugger goes from test method to the code, the builder creates an object reference in the first case i.e. granularity= {Assembly$Partition#3892}, but in the second case, it is giving the reference as null.
Also, sometimes while debugging, it gives me this debug error that Partition cannot be returned by toString().
Edit
Existing test method is this:-
public void publish()
filePublisher.publishFirst(message, event, name);
verify(file publisher, times (1)).publishFile(anyString(), anyList(Mylist.class));
And my new method is:-
public void publish2()
filePublisher.publishSecond(date, id, type);
verify(file publisher, times (1)).publishFile(anyString(), anyList(Mylist.class));
Both methods compute various data to call the publishFile method.
You really have not added enough (real) code to pin this down so don't expect a real answer! Here's a guess:
when(metadata.getGranularity(message))...
... only mocks when that exact message arrives. The publish2 example is
filePublisher.publishSecond(date, id, type);
where date != message.
Try this:
when(metadata.getGranularity(any())).thenReturn(new Assembly.Partition.Builder.build());

How to replace a exact method call in a fluent api using java assist?

I need to replace a method call inside java method.
Consider a scenario :
public void enterCatle(){
if(PaltformRuntime.returnSuggestion()){
System.out.println("entered into the castle");
}
}
I need to replace a returnSuggestion() with some other method call.I am able to achieve this by overriding the edit(MethodCall m) in the
Expression editor of java assist.
But there is a scenario as follows.
public void enterCatle(){
if(PaltformRuntime.returnSuggestion() && ElementRegistry.returnSuggestion()){
System.out.println("entered into the castle");
}
}
Here inside the enterCatle() in the if statement there are 2 returnSuggestion() from different classes. What I need is to replace the first returnSuggestion() alone.
I tried to identify the exact method call to replace by conditions like m.getLineNumber() m.where().getName() with this things I am able to narrow down to the particular method and exact line number. Now the problem is, if the same method is used twice in the same line, both get replaced.
How can I identify the exact method to replace? Is there any way to get the context of the method call like which position the method call is placed so that I can map by java assist.
or is there any other approach for this scenario?

Long commands in Java

I am learning to code in Java
I know what namespaces, classes and methods are
with that knowledge I understand code such as the following
CharSequence v = new BackwardString("whale");
v.toString();
However sometimes you see examples of code which are longer than this
an example being
dictionary.subSet("a","ab").size();
In the ubove example dictionary is a class and subSet() is a method.
However size() is also a method but methods cannot contain other methods, so where does size() come from and why does it work?
Another common example which i have used without giving any thought to until now is
System.out.printLn();
in this case would System be a namespace, out be a class and printLn() be a method?
dictionary.subSet("a","ab").size();
It's a chaining of method calls. dictionary.subSet("a","ab") returns a String object, on which you call the size method.
System.out.println()
System is a class (java.lang.System), out is a static variable of that class whose type is PrintStream, and println is a method of PrintStream.
dictionary.subSet("a","ab").size();
The subSet method returns a String object, you are then calling .size() on this String. It is shorthand for doing the following
String a = dictionary.subSet("a","ab")
int size = a.size();
System.out.println()
System.out returns a PrintStream method, and you are invoking the println() method of that object.
This is called Method Chanining
System.out.printLn();=
System is a class
PrintStream is a class again // ref is out
println() is a function
In this example:
dictionary.subSet("a","ab").size();
method subSet returns an object with method size which gets invoked after subSet returns.
Similar thing happens with another snippet:
System.out.printLn();
Class System contains a static field out which has a method println
This is a common practice in Java programming to pipeline method calls. Sometimes an object can return itself allowing you can call multiple methods in one line.
The . selection is done as follows:
(dictionary.subSet("a","ab")).size();
Set s = dictionary.subSet("a","ab");
s.size();
The method subSet delivers (likely) a Set,
and Set has a method size.
This is called "chaining".
To get a feeling of it:
BigDecimal n = BigDecimal.valueOf("123456780.12");
n = n.multiply(n).add(n).divide(BigDecimal.TWO).subtract(n);
BigDecimal does large numbers with precise fixed point arithmetic.
It cannot use operators, and the above is a normal style.
Selectors (that might be chained:
. member
[ index ]
( function arguments )

Understanding constructors (very simple code)

public class HelloWorldV3
{
//default constructor
HelloWorldV3()
{
}
//print two lines of text
public void printTwoLines( )
{
System.out.println("Hello, Virtual World!");
System.out.println("It is a great day for programming.");
}
//main method
public static void main(String [] args)
{
HelloWorldV3 hello = new HelloWorldV3( );
hello.printTwoLines();
}
Hi, I am beginning to learn about constructors, and I am having trouble understanding some code. In the program above, I know that a constructor was created, but it is empty. The printTwoLines() function prints the two lines, and the main method uses the constructor to call the function. I had questions about why there needs to be the "HelloWorldV3 hello = new HelloWorldV3();" line, and what would happen if there was actually something in the constructor.
The:
HelloWorldV3 hello=new HelloWorldV3();
line makes a variable called hello. Hello is a different type of variable than what you are probably used to, and doesn't store a number, or integer, or anything like that, but an object (really the location of the object, but don't worry about that for now). You could also write it as :
HelloWorldV3 hello;
hello=new HelloWorldV3();
just as you would write:
int i;
i=5;
You can then access either the hello variable or the i variable.
As for the second part of your question, anything in the constructor would be called when the code:
new HelloWorldV3();
is executed. So you could put some code inside the constuctor like this:
public HelloWorldV3() {
System.out.println("In the constuctor");
}
It's just that you allocating the space with new operator for your HelloWorldV3 object.
It's always good to define state in constructor. By state i mean is, if you have say int field, you could initialize it to say default value that might be appropriate when you create your object (say to value 10)
The constructor will initilize your object "hello" of type "HelloWorldV3".
If there is a code in the constructor, it will be executed when calling "new HelloWorldV3( )" in your first line of code of the method. So it will be executed before the method "printTwoLines".
I hope I was clear :)
Thanks.
You need the line
HelloWorldV3 hello = new HelloWorldV3( );
because that is what creates an instance (object) of the class HelloWorldV3, allowing you to call its methods and access its fields (if any).
Java does some things behind the scenes to instantiate an object, and the concept of a constructor exists to allow you to specify code to execute (mostly initialization stuff) when Java is creating an instance of the class.
If there was code in the constructor, that code would execute when the line
HelloWorldV3 hello = new HelloWorldV3( );
executes.
To answer your question with a question, if there wasn't that line, then how would you ever call the printTwoLines() method?

Categories

Resources