This is the custom class which I made:
class BufferedReader{
BufferedReader inClient = null;
public BufferedReader(InputStreamReader stream) {
inClient = new BufferedReader(stream); //points the stackoverflow on this line
}
public String readLine(){
return inClient.readLine();
}
}
So, when I try to access it like below I end up getting a stackoverflow:
BufferedReader[] inClient = new BufferedReader[2];
//using a socket here
inClient[0] = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
Any idea why this is happening?
This gives you a StackOverflowError because you have uncontrolled recursion due to the naming you're using. The constructor will keep calling itself until the stack overflows.
In your constructor you reallocate a new instance of your class which reallocates a new instance of your class... infinitely until you reach the maximum stack size which generates a StackOverflowError.
You should rename your class not to be confused with the one from Java or if you want to keep the name you have to use the full name of the JDK class in your constructor and in the attribute definition: java.io.BufferedReader
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have an enum and I am trying to iterate through it using a foreach and for some reason it is returning null on my first constant. I see nothing wrong with it.
First off, I am creating and initializing a hashmap to store the enums so that I can manipulate them to my heart's content.
public class ScriptLoader {
private ResourceLocation resloc;
private File file;
private FileReader fr;
private BufferedReader br;
//Here
private Map<String, Node> nodes;
Init here:
public void loadScript() throws IOException{
file = resloc.getFile();
fr = new FileReader(file);
br = new BufferedReader(fr);
//Here
nodes = new HashMap<>();
this.setNodes();
if(Engine.stateOfEngine == EnumEngineState.DEBUGGER_ON) {
Engine.LOGGER.log("\tScript Loaded!", EnumLoggerTypes.DEBUG);
}
}
Secondly, I am creating a method called setNodes() which will add the constants to the map in the parent class of setNodes() which is called ScriptLoader.
public void setNodes(){
for(EnumNodes node : EnumNodes.values()) {
nodes.put(node.getName(), node.getNode());
}
}
And I am calling it here:
public void loadScript() throws IOException{
file = resloc.getFile();
fr = new FileReader(file);
br = new BufferedReader(fr);
nodes = new HashMap<>();
this.setNodes();
if(Engine.stateOfEngine == EnumEngineState.DEBUGGER_ON) {
Engine.LOGGER.log("\tScript Loaded!", EnumLoggerTypes.DEBUG);
}
}
Now, I have an enum that I have a list of "nodes" that I want to iterate through, which can be seen in the setNodes() method.
Now the crash report is here. For some reason, it is pointing the ExceptionInInitializationError at the first enum constant, and the null pointer exception at the enum declaration. I didn't think that an enum declaration could return null.
From that error message, I'm guessing that something in your enum constructor is throwing an exception. Digging through your github a bit, I believe that the problem is in Node. It looks like the enums may be initialized by Java's classloader before start is called on an instance of Engine, causing Engine.getScriptLoader() to return null, and Node's constructor to throw a NullPointerException.
What I want to do is to mock newly created instance of BufferedReader. Here's the code that should be tested:
A.java
...
#Override
public String read(String fileName) throws IOException {
...
try {
fileReader = new FileReader(fileName);
bufferedReader = new BufferedReader(fileReader);
String tmp;
StringBuilder builder = new StringBuilder();
while ((tmp = bufferedReader.readLine()) != null) {
builder.append(tmp);
}
return builder.toString();
} catch (IOException e) {
...
} finally {
...
}
}
...
What I have to do, is to PowerMock both FileReader creation and BufferedReader creation.
ATest.java
#RunWith(PowerMockRunner.class)
#PrepareForTest(A.class)
public class ATest {
#Mock
private FileReader fileReader;
#Mock
private BufferedReader bufferedReader;
...
#Test
public void test() throws Exception {
PowerMockito.whenNew(FileReader.class).withArguments(FILE_NAME).thenReturn(fileReader);
PowerMockito.whenNew(BufferedReader.class).withAnyArguments().thenReturn(bufferedReader);
PowerMockito.doAnswer(new Answer() {
public Object answer(InvocationOnMock invocation) throws Throwable {
return "test";
}
}).when(bufferedReader).readLine();
assertArrayEquals(reader.read(FILE_NAME), new String[]{"test"});
}
}
But then the test never terminates. I can't even debug it.
As soon as PowerMockito.doAnswer() is removed the code is executed (and is available for debugging). I've also tried to use Mockito.mock() instead of PowerMockito.doAnswer(), it doesn't help.
What may cause interminate execution of the test?
Just a different perspective: one could say that your real problem in your code are those two calls to new() for FileReader / BufferedReader.
What if you passed a Reader to this method; instead of a String denoting a file name?
What if you passed a "ReaderFactory" to the underlying class that contains this method read(String)? (where you would be using dependency injection to get that factory into your class)
Then: you would be looking at an improved design - and you would not need to use PowerMock. You could step back and go with Mockito or EasyMock; as there would be no more need to mock calls to new.
So, my answer is: you created hard-to-test code. Now you try to fix a design problem using the big (ugly) PowerMock hammer. Yes, that will work. But it is just the second best alternative.
The more reasonable option is to learn how to write testable code (start here for example); and well, write testable code. And stop using PowerMock ( I have done that many months back; after a lot of PowerMock-induced pain; and I have never ever regretted this decision ).
The problem was, that I also had to mock value after first bufferedReader.readLine(), because otherwise it would always return the mocked value, thus not terminating.
Mockito.when(bufferedReader.readLine()).thenReturn("first line").thenReturn(null);
NOTE
Though this is the actual answer to the question, but you should strongly consider choosing the design GhostCat has suggested in another answer (which I eventually did).
So I'm coming back to Java after a long time of not working with it. First method of my first class and I'm seeing an error I've never seen before.
For every System.out.println() statement I have, the .out. part throws this error:
cannot find symbol
symbol: variable out
location: class System
my class is unfinished but looks like this
import java.io.*;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class System{
//Variables
char map[];
/*
Functions
FILE INPUT
*/
public static void ReadFile(){
FileInputStream fstream;
try{
fstream = new FileInputStream("C:\\Users\\James\\Documents\\NetBeansProjects\\Assignment1\\src\\testfiles");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
System.out.println("Your Input File");
System.out.println("****************");
//Read File Line By Line
while ((strLine = br.readLine()) != null)
{
// Print the content on the console
System.out.println(strLine);
inputArray.add(strLine);
}
System.out.println("****************");
//Close the input stream
br.close();
System.out.println();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
Every single .out. in this block of code throws this error :cannot find symbol
symbol: variable out
location: class System
I am using Netbeans8.0.2 and java 1.7.0_76(because I have to)
Can someone shed some light on this?
This is the problem:
public class System
You're creating your own class called System, so when you later use:
System.out.println
that's looking in your System class rather than java.lang.System.
Options:
Change the name of your class. It's generally a bad idea to create classes with the same name as classes within java.lang, precisely for this reason
Fully-qualify the call:
java.lang.System.out.println(...);
I'd pick the former option, personally.
Replace all the System.<something> with java.lang.System.<something>.
In its current state, your code is referencing your own System class. Since the name is the same, and yours has a higher priority in the scope, you end up with this error.
It's probably a better idea to change the name of your class. You generally don't want to conflict with internal names.
When you are using System.out.println() in the same class name System . So at the time of calling method println() your program searching the method in same class instead of checking same in java.lang. package.
So as for the solution of issue , either you can change the name of class to some thing else rather than System or you can change System.out.println() with java.lang.System.out.println().
I have a text file and that file lists all the operations that can be performed on a Pump Class.
example of the content of text file
Start PayCredit Reject Start PayCredit Reject TurnOff
....
.... so on.
These are the methods of the Pump class(Start(), Reject() etc)
I need to write a code where I can Read these method from the file one by one and execute them.
public static void main(String[] args) throws IOException
{
Pump gp= new Pump();
File file=new File("C:\\Users\\Desktop\\checker\\check.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line=null;
while((line=br.readLine())!=null)
{
String words[]=line.split(" ");
for(int i=0;i<words.length;i++)
{
String temp=words[i]+"()";
gp.temp; //compilation error
}
}
}
Could you tell me how can I achieve this functionality.
If you're not so familiar with reflection, maybe try using org.springframework.util.ReflectionUtils from the Spring Framework project?
The code would go something like this:
Pump gp = new Pump();
....
String temp = // from text file
....
Method m = ReflectionUtils.findMethod(Pump.class, temp);
Object result = ReflectionUtils.invokeMethod(m, gp);
You would need to use reflection to invoke the methods at runtime. Here is a simple example that assumes that all methods do not take any parameters.
Class<? extends Pump> pumpClass = gp.getClass();
String methodName = words[i];
Method toInvoke = pumpClass.getMethod(methodName);
if (null != toInvoke) {
toInvoke.invoke(gp);
}
First of all be aware that Java is not interpreted at runtime. So you can't do it this way.
If you already have the methods such as Start PayCredit Reject TurnOff and so on you can do it in the following way:
for(int i=0;i<words.length;i++)
{
String temp=words[i];
if (temp.equals("Start") gp.Start();
else if (temp.equals("PayCredit") gp.PayCredit();
...
}
use a switch case
for(int i=0;i<words.length;i++) {
String temp=words[i];
switch(temp) {
case "Start":
gp.start();
break;
case "PayCredit":
gp.PayCredit();
break;
}
}
You can use reflection to do this, e.g.
String line=null;
Method method = null;
while((line=br.readLine())!=null)
{
String words[]=line.split(" ");
for(int i=0;i<words.length;i++)
{
String temp=words[i];
method = getClass().getMethod(temp);
method.invoke(this);
}
}
That's assuming you want to call the method on this, of course, and that it's an instance method. Look at Class.getMethod and related methods, along with Method itself, for more details. You may want getDeclaredMethod instead, and you may need to make it accessible.
I would see if you can think of a way of avoiding this if possible though - reflection tends to get messy quickly. It's worth taking a step back and considering if this is the best design. If you give us more details of the bigger picture, we may be able to suggest alternatives.
this is my first post here. I have recently started to get interested in learning Java, I have read through some beginner level tutorials, kept http://docs.oracle.com as my bookmark and read several sample codes.
Now messing with my own for practice I discovered something weird for which I couldn't find any satisfying answer in manuals/tutorials/documentation.
Theres a little class I produced to practice IO, and queue style objects. It is meant to create an object containing file name, and an empty linkedlist. Then it has a method for that given file to be read and lines from that added one by one to the linkedlist queue.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.LinkedList;
public class Handle
{
public File filehandle;
public LinkedList<String> queue;
Handle (File filename)
{
filehandle=filename;
LinkedList<String> queue = new LinkedList<String>();
}
public void addq()
{
try{
FileReader ava;
ava = new FileReader(filehandle);
//without initializing new linekedlist queue it'll give NPE in queue.add
//why can't it use class/instance variable queue it does fine with filehandle
queue = new LinkedList<String>();
BufferedReader br = null;
String sCurrentLine;
br = new BufferedReader(ava);
while ((sCurrentLine = br.readLine()) != null)
{
queue.add(sCurrentLine);
}
queue.offer("POISON");
}
catch (IOException e) {e.printStackTrace();}
}
The weird thing - When tried to use class variable/instance variable queue (public LinkedList queue) declared in class, the one also initiated in constructor, inside the method, it compiled fine but at the runtime it threw NPE at queue.add lines. NPE faded as I initialized method variable queue inside method. Why can't the method add to class variable queue? It seems to use the fielhandle variable just fine!
Also as shown by the poll method result in code running the class(posting it down) - it still seems to actually add the lines into the instance variable queue not just temporary method variable. (Which is of course good but I do not understand how and why)
Down here is the code that I used to run the Handle class in.
import java.io.File;
import java.util.LinkedList;
class Runner
{
public static void main(String[] args)
{
File file = new File("proovidest.csv");
Handle handle =new Handle(file);
//using the constructor, now we have object with filehandle and empty queue variables
handle.addq();
String mison;
//so apparently the instance variable queue is still filled with lines (good)
//but how? the method had to delcare its own variable (why), but still the class field is //now filled? how?
while ((mison = handle.queue.poll()) != "POISON")
{System.out.println(mison);}
}
}
So can anybody give me good explanation why I couldn't acess the class variable queue in method in runtime, although I was able to use filehandle variable.
What SHOULD I do to access it then?
Can anybody tell me how the class field queue then still got filled, although I declared a new variable inside the method. Or does the handle.queue.poll somehow detect variables form methods?
The problem is here:
Handle (File filename) {
filehandle=filename;
LinkedList<String> queue = new LinkedList<String>();
}
You don't initialize the instance field queue, rather you create a new local variable with the same name, which is valid only in the constructor. Change it to:
Handle (File filename) {
filehandle=filename;
queue = new LinkedList<String>();
}
and it should not throw a NPE.
Inside your constructor, you declared a local variable queue, hiding your class variable!
Handle (File filename)
{
filehandle=filename;
this.queue = new LinkedList<String>();
}
The problem is the visibility of your LinkedList. It is only visible in your private constructor. To use the queue LinkedList just write this in your constructor:
queue = new LinkedList<String>();
furthermore remove that in addq:
queue = new LinkedList<String>();
Looks there is no place to fire NPE on your code.
It will fire File not found exception if mention file not in location.
Can you post stack trace to more investigations.