How to get the value which I sent via System.out.println? - java

Sorry I searched a lot but could not find an answer to it. If there is , I a apologize and please let me know.
If I have sent an value via System.out.println or .print is there any way to get it ? I mean after sending get all values sent via System.out and the last sent value ?
System.out.println("Hi");
String val = System.\\something
String last = System.\\something else
Thank you

I guess below code will be useful for you :
Create a class and extend PrintStream
class StorePrintStream extends PrintStream {
public static List<String> printList = new LinkedList<String>();
public StorePrintStream(PrintStream org) {
super(org);
}
#Override
public void println(String line) {
printList.add(line);
super.println(line);
}
public void println(int line) {
this.println(String.valueOf(line));
}
// And so on for double etc..
}
Now use above class to track print information :
public class Test {
public static void main(String[] args) throws Exception {
System.setOut(new StorePrintStream(System.out));
System.out.println("print line");
Test2 t2 = new Test2();
t2.meth1();
System.out.println(StorePrintStream.printList);
}
}
class Test2 {
public void meth1() {
System.out.println("another print");
}
}

There seems to be a bit of a misunderstanding of what System.out.println does. System.out.println sends a String to the Outputstream (stdout) of the Java program. So it is returned to the operation system. That is generally used, to make an output visible to the user, but also to other applications. Another application could read that with System.in.read.
In your case you would like to use the output in the same application, which is unnecessary, because the application knows its own data.
If you need to store a history of the outputted data, you can certainly save the history in you own application - (as suggested in a comment) a decorated PrintStream could do the job.
If you are a Beginner with Java, it might be easier to write a new method that stores your history. Eg. you could add the following to your class:
private static LinkedList<String> stdoutHistory;
public static void betterPrintln(String s)
{
System.out.println(s);
stdoutHistory.add(s);
}
// this method returns the last printed output
public static String getLastOutput()
{
return stdoutHistory.get(stdoutHistory.count()-1);
}
and then call that method, to print something

Related

Get value of System.out.println from main method called via reflection

I'm calling the main method of a class via reflection. For example:
Object o = clasz.getDeclaredConstructor().newInstance();
Method method = clasz.getMethod("main", String[].class);
method.invoke(o, new String[1]);
The called code looks as:
public class Test {
public static void main(String[] args) {
System.out.println("This is a test");
}
}
The reflection works fine and I can see the message in the console.
Is there a way to register something like a binding to the method invocation, for example a PrintWriter or a custom decorated Writer, so I can get the print value as a String?
You can change what System.out is bound to using System.setOut();. You can then make your own:
public class MyTeeingPrinter extends OutputStream {
private final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
private final PrintStream original;
public MyTeeingPrinter(PrintStream original) {
this.original = original;
}
#Override public void write(int b) {
original.write(b);
buffer.write(b);
}
public String getAndClear() {
String s = buffer.toString(StandardCharsets.UTF_8);
buffer.reset();
return s;
}
}
And then:
MyTeeingPrinter tee = new MyTeeingPrinter();
System.setOut(new PrintStream(tee));
and now you can invoke tee.getAndClear().
It's a bit of a slog, because whatever code you are running like this is presumably badly designed - it should have instead taken a PrintStream or preferrably an Appendable or Writer, and would write into this writer. Then a trivial one-liner main can be made that just tosses System.out into a writer and hands that to this code you're attempting to run for the case where you just want that code to run and write to sysout, and you can make your own (and stop using reflecting to invoke that main method) and hand that to this code you are running in this scenario.
Note that your reflective code 'works' but is bizarre. There is no need to make a new instance; main is static. The right way is:
Method method = clasz.getMethod("main", String[].class);
method.invoke(null, new String[1]);
That main() method is called in the same process, hence, you can just provide your own stdout implementation/decorator via java.lang.System.setOut(PrintStream) before the reflection magic
An empty string array would work: new String[1] -> new String[0]
You don't need to create a new object to call the static method. Even though java allows calling static methods via objects, this is a bad style and sometimes might cause problems because of name shadowing. Consider the example below:
public class Parent {
public static void main(String[] args) {
Parent child = new Child();
child.test();
}
public static void test() {
System.out.println("Parent.test()");
}
}
class Child extends Parent {
public static void test() {
System.out.println("Child.test()");
}
}
It actually calls Parent.test() even though it's invoked on a Child object

Is there any straightforward way to fetch and send `current method name` as argument in java?

Making an api to log and provide common methods.
public static void start(Class<?> clazz) throws IOException {
writeExecutionLog("Start of" + clazz.getName(), null);
}
public static void end(Class<?> clazz) throws IOException {
writeExecutionLog("End of" + clazz.getName(), null);
}
In classes, There are multiple schedulers in different methods which calls above start and end when job is started or finsihed.
class scheduler{
public void scheduler1(){
MyService.start(methodname or class)
MyService.end(methodname or class)
}
public void scheduler2(){
MyService.start(methodname or class)
MyService.end(methodname or class)
}
}
In place of String, is there any simple way to pass Method name with class name in above start and end method.
I want to fetch current method name dynamically in Start and end methods something like this.class.currentMethod?(not complicated statement like mentioned in geekofgeeks and better if i can handle most of things in start() and end())
You could generate a stack trace and parse the line. It's versatile but expensive.
public static void start() throws IOException {
writeExecutionLog("Start of" + new Throwable().getStackTrace()[1].getMethodName(), null);
}
String methodName = new Object() {}
.getClass()
.getEnclosingMethod()
.getName();
in your method should work.
You are reinventing the wheel, as logging APIs do already exist and are capable of identifying the method.
Taking the built-in logging API java.util.logging.*, a very simple example demonstrating the capability would be
public class MethodNameExample1 {
static final Logger MY_SERVICE = Logger.getAnonymousLogger();
static {
MY_SERVICE.setUseParentHandlers(false);
MY_SERVICE.addHandler(new Handler() {
public void publish(LogRecord lr) {
System.out.println(lr.getSourceClassName()+"."+lr.getSourceMethodName()
+" "+lr.getMessage()+"ed");
}
public void flush() {}
public void close() {}
});
}
public static void main(String[] args) {
MY_SERVICE.info("enter");
firstExample();
Inner.thirdExample();
MY_SERVICE.info("exit");
}
static void firstExample() {
MY_SERVICE.info("enter");
secondExample();
MY_SERVICE.info("exit");
}
static void secondExample() {
MY_SERVICE.info("enter");
MY_SERVICE.info("exit");
}
static class Inner {
static void thirdExample() {
MY_SERVICE.info("enter");
//...
MY_SERVICE.info("exit");
}
}
}
MethodNameExample1.main entered
MethodNameExample1.firstExample entered
MethodNameExample1.secondExample entered
MethodNameExample1.secondExample exited
MethodNameExample1.firstExample exited
MethodNameExample1$Inner.thirdExample entered
MethodNameExample1$Inner.thirdExample exited
MethodNameExample1.main exited
When you want to have more control over this (or insist on creating your own logging API implementation), Java 9’s StackWalker is the way to go. Unlike capturing a stack trace like with new Throwable().getStackTrace(), the stack walker supports extracting only the needed information, including hinting about the maximum number of frames we intend to traverse, so the JVM doesn’t need to process more than necessary and may apply further optimizations:
public class MethodNameExample2 {
public static class MyService {
private static final StackWalker STACK_WALKER=StackWalker.getInstance(Set.of(), 3);
public static void enter() {
System.out.println(getCaller()+" entered");
}
public static void exit() {
System.out.println(getCaller()+" exited");
}
private static String getCaller() {
return STACK_WALKER.walk(frames -> frames.skip(2)
.map(f -> f.getClassName()+'.'+f.getMethodName())
.findFirst().orElse("unknown caller"));
}
}
public static void main(String[] args) {
MyService.enter();
firstExample();
Inner.thirdExample();
MyService.exit();
}
static void firstExample() {
MyService.enter();
secondExample();
MyService.exit();
}
static void secondExample() {
MyService.enter();
MyService.exit();
}
static class Inner {
static void thirdExample() {
MyService.enter(); MyService.exit();
}
}
}
MethodNameExample2.main entered
MethodNameExample2.firstExample entered
MethodNameExample2.secondExample entered
MethodNameExample2.secondExample exited
MethodNameExample2.firstExample exited
MethodNameExample2$Inner.thirdExample entered
MethodNameExample2$Inner.thirdExample exited
MethodNameExample2.main exited
Your task should be done using AOP (Aspect oriented programming)
[AOP] aims to increase modularity by allowing the separation of cross-cutting concerns. It does so by adding additional behavior to existing code (an advice) without modifying the code itself, instead separately specifying which code is modified via a "pointcut" specification, such as "log all function calls when the function's name begins with 'set'".
For example, you can mark all your scheduler methods with a custom annotation (or use method name, package name etc.) and the create an aspect
#Around("#annotation(LogExecutionTime)")
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
logger.debug("start of ...")
Object proceed = joinPoint.proceed();
logger.debug("end of ...")
return proceed;
}
from ProceedingJoinPoint you can extract a lot of information not just method name.

Simple pass of variable to new class, then output in Java

I've seen this question asked in several ways, but the code is usually specific to the user, and I get lost a little. If I'm missing a nice clear and simple explanation, I'm sorry! I just need to understand this concept, and I've gotten lost on the repeats that I've seen. So I've simplified my own problem as much as I possibly can, to get at the root of the issue.
The goal is to have a main class that I ask for variables, and then have those user-inputted variables assessed by a method in a separate class, with a message returned depending on what the variables are.
import java.io.*;
public class MainClass {
public static void main(String[] args) {
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
String A;
String B;
try {
System.out.println("Is A present?");
A = reader.readLine();
System.out.println("Is B present?");
B = reader.readLine();
Assess test = new Assess();
} catch (IOException e){
System.out.println("Error reading from user");
}
}
}
And the method I'm trying to use is:
public class Assess extends MainClass {
public static void main(String[] args) {
String A = MainClass.A;
String B = MainClass.B;
if ((A.compareToIgnoreCase("yes")==0) &&
((B.compareToIgnoreCase("yes")==0) | (B.compareToIgnoreCase("maybe")==0)))
{
System.out.println("Success!");
}
else {
System.out.println ("Failure");
}
}
}
I recognize that I'm not properly asking for the output, but I can't even get there and figure out what the heck I'm doing there until I get the thing to compile at all, and I can't do THAT until I figure out how to properly pass values between classes. I know there's fancy ways of doing it, such as with arrays. I'm looking for the conceptually simplest way of sending a variable inputted from inside one class to another class; I need to understand the basic concept here, and I know this is super elementary but I'm just being dumb, and reading what might be duplicate questions hasn't helped.
I know how to do it if the variable is static and declared globally at the beginning, but not how to send it from within the subclass (I know it's impossible to send directly from the subclass...right? I have to set it somehow, and then pull that set value into the other class).
In order to pass variables to an object you have either two options
Constructor - will pass parameter when creating the object
Mutator method - will pass parameters when you call the method
For example in your Main class:
Assess assess = new Assess(A, B);
Or:
Assess assess = new Assess();
assess.setA(A);
assess.setB(B);
In your Assess class you have to add a constructor method
public Assess(String A, String B)
Or setter methods
public void setA(String A)
public void setB(String B)
Also, Assess class should not extend the main class and contain a static main method, it has nothing to do with the main class.
Below there is a code example!
Assess.java
public class Assess {
private a;
private b;
public Assess(String a, String b) {
this.a = a;
this.b = b;
}
public boolean check() {
if ((A.compareToIgnoreCase("yes")==0) &&
((B.compareToIgnoreCase("yes")==0) ||
(B.compareToIgnoreCase("maybe")==0)))
{
System.out.println("Success!");
return true;
} else {
System.out.println ("Failure");
return false;
}
MainClass .java
public class MainClass {
public static void main(String[] args) {
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
String A;
String B;
try {
System.out.println("Is A present?");
A = reader.readLine();
System.out.println("Is B present?");
B = reader.readLine();
Assess test = new Assess(A, B);
boolean isBothPresent = test.check();
// ................
} catch (IOException e){
System.out.println("Error reading from user");
}
}
I think what you're looking for are method parameters.
In a method definition, you define the method name and the parameters it takes. If you have a method assess that takes a string and returns an integer, for example, you would write:
public int assess(String valueToAssess)
and follow it with code to do whatever you wanted with valueToAssess to determine what integer you wanted to return. When you had decided that i was the int to return, you would put the statement
return i;
into the method; that terminates the method and returns that value to the caller.
The caller obtains the string to be assesed, then calls the method and passes in that string. So it's more of a push than a pull, if you see what I mean.
...
String a = reader.readLine();
int answer = assess(a);
System.out.println("I've decided the answer is " + answer);
Is that what you're looking for?
A subclass will have access to the public members of the superclass. If you want to access a member using {class}.{member} (i.e. MainClass.A) it needs to be statically declared outside of a method.
public class MainClass {
public static String A;
public static String B;
...
}
public class Subclass {
public static void main(String[] args) {
// You can access MainClass.A and MainClass.B here
}
}
Likely a better option is to create a class that has these two Strings as objects that can be manipulated then passed in to the Assess class
public class MainClass {
public String A;
public String B;
public static void main(String[] args) {
// Manipulate A, B, assign values, etc.
Assess assessObject = new Assess(A, B);
if (assessObject.isValidInput()) {
System.out.println("Success!");
} else {
System.out.println("Success!");
}
}
}
public class Assess {
String response1;
String response2;
public Assess (String A, String B) {
response1 = A;
response2 = B;
}
public boolean isValidInput() {
// Put your success/fail logic here
return (response1.compareToIgnoreCase("yes") == 0);
}
}
First you don't need inheritance. Have one class your main class contain main take the main out of Assess class. Create a constructor or setter methods to set the variables in the Assess class.
For instance.
public class MainClass
{
public static void main(String[] Args)
{
Assess ns = new Assess( );
ns.setterMethod(variable to set);
}
}
I'm not 100% sure of your problem, but it sounds like you just need to access variables that exist in one class from a subclass. There are several ways...
You can make them public static variables and reference them as you show in your Assess class. However, they are in the wrong location in MainClass use
public static String A, B;
You can make those variables either public or protected in the parent class (MainClass in your example). Public is NOT recommended as you would not know who or what modified them. You would reference these from the sub-class as if present in the sub-class.
public String A, B; // Bad practice, who modified these?
protected String A, B;
The method that might elicit the least debate is to make them private members and use "accessors" (getters and setters). This makes them accessible programmatically which lets you set breakpoints to catch the culprit that is modifying them, and also let you implement many patterns, such as observer, etc., so that modification of these can invoke services as needed. If "A" were the path to a log file, changing its value could also cause the old log to close and the new one to be opened - just by changing the name of the file.
private String A, B;
public setA(String newValue) {
A = newValue;
}
public String getA() {
return A;
}
BUT ...
Your question says "send to the subclass", but confounded by your knowing how to do this using global variables. I would say that the simplest way is to provide the values with the constructor, effectively injecting the values.
There are other ways, however, your example shows the assessment performed by the constructor. If your Assess class had a separate method to perform the assessment, you would just call that with the variables as arguments.
Your example is confusing since both classes have main methods and the child class does the assessing - I would think you would want the opposite - Have MainClass extend Assess, making "MainClass an Assess'or", let main assign the Strings to Assess' values (or pass them as arguments) to the parent class' "assess" method ("super" added for clarity):
super.setA(local_a);
super.setB(local_b);
super.assess();
or
super.assess(A, B);

Multiple classes basics, putting a print class into the main method

I am trying to see the basics for what is required to call in a second class, because tutorials and the book I am using are over-complicating it by using user input right now.
So here is what I tried. First is my main class and the second is the class I tried to call into the main method portraying just a simple text.
public class deck {
public static void main(String[] args) {
edward test = new edward();
System.out.print(test);
}
}
Other class:
public class edward {
public void message(int number) {
System.out.print("hello, this is text!");
}
}
How come this doesn't work?
If you could try to explain what I am doing or how this works a bit in detail that would be nice. I'm having a hard time with this part and getting a bit discouraged.
This does not work because you are printing a wrong thing: rather than printing test, you should call a method on it, like this:
public class deck {
public static void main(String[] args){
edward test = new edward();
test.message(123);
}
}
message(int) is a method (more specifically, an instance method). You call instance methods by specifying an instance on which the method is to be called (in your case, that is test), the name of the method, and its parameters.
The other kind of methods is static - i.e. like main. These methods do not require an instance, but they cannot access instance properties either.
Just an additional hint.
Every class in Java is derived from the java built in class "Object".
This common class offers some common methods.
In your case the method
public String toString()
is from interest.
You can override this method in your class edward and return the String you want.
public class edward {
#override
public String toString() {
return "hello, this is text!"
}
}
If you now use an object of class edward (test)t within the main method like you did it in your sample code
public static void main(String[] args) {
edward test = new edward();
System.out.println(test);
}
Then the text returnrd by the overriden toString() method would be printed out.
You use in this case the possibility to override methods from a super class (Object) and a subclass (edward).
Generally you would use the toString nethod to output the values of the fields (properties) of an object to show its current state.
If you not override the toString method you would get a String like eg this #ae23da which represents the current adress of the object test in memory.
public class deck
{
public static void main(String[] args)
{
edward test = new edward(); //1
System.out.print(test); //2
}
}
In line 1, you create a new edward object called test.
In line 2, you print the object itself. According to the Java API, print(Object)
Prints an object. The string produced by the String.valueOf(Object) method is translated into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.
I'm guessing that the output looked something like: edward#672563. That is because String.valueOf(obj) returns the type of obj (edward), followed by the character #, followed by the location in memory of obj (672563).
Here is some code that should do what you are attempting:
public class Deck //all class names should be capitalized
{
public static void main(String[] args)
{
Edward test = new Edward();
test.message(); //1
}
}
public class Edward
{
public void message() //`message` doesn't need a parameter
{
System.out.print("hello, this is text!");
}
}
In line 1, you call test's method message(). Calling a method executes the code that is in that method, so test.message() executes the line
System.out.print("hello, this is text!");
Here is a different way of doing the same thing:
public class Deck
{
public static void main(String[] args)
{
Edward test = new Edward();
System.out.println(test.message); //1
}
}
public class Edward
{
public String message = "hello, this is text!"; //2
}
In line 2, you create a new String "field" with the value of "hello, this is text!".
In line 1, you print the value of the field message contained in the object test.
If there are other parts of this code that you don't understand, feel free to comment on this answer!

Writing a Java class with instance parameters, retrieve parameters and print results

Basically, I need to create a new simple Java class which retrieves values from my forms (that I have designed as my process and is deployed as a web application), once the method in the Java class is invoked then the Java class should just simply print out the values (e.g. system.println.out...) it got from the form in a console or text file.
Create a class with some instance parameters. Print a line stating the initial values of these parameter(s).
I am new to Java and have just started few days ago but have this requirement as part of a project.
Please someone help to write this Java class.
I recommend you to read some java beginners books (or the javadoc) in order to understand the Class constructor concept in java before trying to do write something wrong.
A rough class may be like this :
public class myClass{
int param1;
int param2;
public myClass(int firstparam, int secondparam){
this.param1 = firstparam;
this.param2 = secondparam;
}
}
public static void main(){
myClass c = new myClass(1,2);
System.out.println(c.param1 + c.param2);
}
If you don't understand this, please learn the java basis..
You can simply create a class and its constructer like:
public class Test {
//a string representation that we will initialize soon
private String text;
//Firstly you have to instantiate your Test object and initialize your "text"
public Test(String text) {
this.text = text;
//System.out.println(text);
//You can print out this text directly using this constructor which also
//has System.out.println()
}
//You can just use this simple method to print out your text instead of using the
//constructor with "System.out.println"
public void printText() {
System.out.println(this.text);//"this" points what our Test class has
}
}
While using this class is like:
public class TestApp {
public static void main(String[] args) {
Test testObject = new Test("My Text");
/*if you used the constructor with System.out.println, it directly prints out
"My Text"*/
/*if your constructor doesn't have System.out.println, you can use our
printText() method //like:*/
testObject.printText();
}
}

Categories

Resources