Way to print the variable name and variable value in java - java

String activityState = "resume";
DebugLog(activityState)
void DebugLog(String obj1) {}
How to make the DebugLog to print like this:
activityState : resume
I used to write many print statement as logs at many places while debugging. I will write statements like
System.out.println("activityState : " + activityState);
I want a method to print the variable name and variable value. In C++, it can be done like the below:
#define dbg(x) cout<< #x <<" --> " << x << endl ;
Is there any way to do this?
Thanks in advance.

There's no direct solution to get the variable name.
However, in a context where you have many fields and don't want to manually print their state, you can use reflection.
Here's a quick example:
class MyPojo {
public static void main(String[] args) {
System.out.println(new MyPojo());
}
int i = 1;
String s = "foo";
#Override
public String toString() {
StringBuilder result = new StringBuilder();
for (Field f: getClass().getDeclaredFields()) {
try {
result
.append(f.getName())
.append(" : ")
.append(f.get(this))
.append(System.getProperty("line.separator"));
}
catch (IllegalStateException ise) {
result
.append(f.getName())
.append(" : ")
.append("[cannot retrieve value]")
.append(System.getProperty("line.separator"));
}
// nope
catch (IllegalAccessException iae) {}
}
return result.toString();
}
}
Output
i : 1
s : foo

You can use java Reflection to get the variable name and the value. Here's an example code;
public class Example{
String activityState = "resume";
public static void main(String[] args) {
Example example = new Example();
Class<?> c = example.getClass();
Field field = c.getDeclaredField("activityState");
System.out.println(field.getName());
System.out.println(field.get(example));
}
}

Since this is for debugging you could use instrumentation with aspectj, your code remains clean from the the debugging output statements and you can waeve the aspect as needed.
Define a set(FieldPattern) point cut to catch all field assignements (join points)
public aspect TestAssignmentAspect {
pointcut assigmentPointCut() : set(* *);
after() : assigmentPointCut() {
System.out.printf("%s = %s%n", thisJoinPoint.getSignature().getName(),
String.valueOf(Arrays.toString(thisJoinPoint.getArgs())));
}
}
Here is Test class
public class Test {
public static String activityState = "stopped";
public static void main(String[] args) {
activityState = "start";
doSomething();
activityState = "pause";
doSomeOtherthing();
activityState = "resume";
System.out.printf("the end!%n");
}
private static void doSomeOtherthing() {
System.out.printf("doing some other thing...%n");
}
private static void doSomething() {
System.out.printf("doing something...%n");
}
}
If you run this example with the aspect weaved the output will be
activityState = [stopped]
activityState = [start]
doing something...
activityState = [pause]
doing some other thing...
activityState = [resume]
the end!
Explanation
pointcut assigmentPointCut() : set(* *);
set point cut to catch assignments, the point joins, to any variable with any name, could also in the example be
pointcut assigmentPointCut() : set(String activityState);
The advice, the desired behavior when the given point cut matches
after() : assigmentPointCut() { ... }
Informations about the point join can be accessed using the special reference thisJoinPoint.

Related

Method containing interface as parameter

hello how do I call a method taking an interface as a parameter from the main ?
The code in the main is an example of what I want to achieve but by calling the method map now
What do I write in my map method and how do I call it in the main ? Thank you
What I want to achieve :
StringTransformation addBlah = (e) -> {
e += "boo";
return e;
};
System.out.println(addBlah.transf("Hello")); // prints Helloboo
public class Main{
public static void main(String[] args) {
String a = hello;
// How do I modify the string a by calling map ?
}
void map(StringTransformation t) {
// What do I write ??
}
}
public interface StringTransformation {
String transf(String s);
}
You want to modify a String with a given StringTransformation so you need to pass both of them to the map method. Also you can turn addBlah in a more simple lambda :
public static void main(String[] args) {
StringTransformation addBlah = (e) -> e + "boo";
String str = "Hello";
System.out.println(str); // Hello
str = map(addBlah, str);
System.out.println(str); // Helloboo
}
static String map(StringTransformation t, String argument) {
return t.transf(argument);
}
You cannot call map inside the static main method. You must make map a static method as well if you want to do that. Also we can't help you with what to put inside your map function if you don't tell us what it should do.
public static void main(String[] args) {
String string = "Hello";
// you can call `mapBoo` like normal here
string = mapBoo(string);
System.out.println(string);
List<String> strings = Arrays.asList("Hello", "this", "is", "a", "test");
// or you can pass mapBoo into the stream.map method since map fits the method signature
List<String> mappedStrings = strings.stream().map(Main::mapBoo)
.collect(Collectors.toList());
for (String mappedString : mappedStrings)
System.out.println(mappedString);
}
static String mapBoo(String s) {
return s + "boo";
}

Java parser for Netbeans?

Is there a plugin or parser for Netbeans that can create a tree structure out of my Java source code(or otherwise let me easily extract things like class names, attributes and methods)?
Edit: I need the names for programming purposes, not just to get them. I need them to be returned to my program at runtime.
If I have this source code(for a game):
class Main {
Terrain terrain;
TradingSystem currentSystem;
City city;
public static void main(String[] args) {
}
}
class Terrain {
}
class City {
House tavern;
}
class TradingSystem {
Bank cityBank;
Trader npc1;
}
then I need a parser than can create something like this
----------Main-------------------
| | |
Terrain City --TradingSystem---
| | |
House Bank Trader
from my source code. I need a path from Main to the branches, like this Main->TradingSystem->Bank, or this Main->City->House.
I need to be able to extract the
Class names
Method names
Attribute names
I need it for a Netbeans plugin I'm creating. Does this exist, free to use/download?
Edit: If there exist something for extracting the class names, attribute names and method names from one and one source file that is a good second option. I can write the additional logic from there.
I have created 3 simple classes:
public class A {
B b;
}
public class B {
C c;
public C getC() {
return c;
}
}
public class C {
}
And another slightly complex:
public class SO {
A a;
B b;
C c;
public static void fooMethod1() {
}
public String fooMethod2() {
return "";
}
private double fooMethod3() {
return 0.0;
}
}
I was able to extract the information above through this recursive code:
public void getData(Map<String, Set<String>> fields, Map<String, Set<String>> methods, Class clazz)
{
if(clazz.isPrimitive())
{
return;
}
for(Method method : clazz.getDeclaredMethods())
{
if(!methods.containsKey(clazz.getName()))
{
Set<String> methodNames = new HashSet<>();
methodNames.add(method.getName());
methods.put(clazz.getName(), methodNames);
}
else
{
methods.get(clazz.getName()).add(method.getName());
}
}
for(Field field : clazz.getDeclaredFields())
{
if(!fields.containsKey(clazz.getName()))
{
Set<String> fieldNames = new HashSet<>();
fieldNames.add(field.getName());
fields.put(clazz.getName(), fieldNames);
}
else
{
fields.get(clazz.getName()).add(field.getName());
}
getData(fields, methods, field.getType());
}
}
I called the code above like so:
SO so = new SO();
Map<String, Set<String>> methods = new HashMap<>();
Map<String, Set<String>> fields = new HashMap<>();
so.getData(fields, methods, SO.class);
And printed the results like so:
for(String str : fields.keySet())
{
System.out.println(str);
for(String fieldName : fields.get(str))
{
System.out.print(fieldName + " ");
}
System.out.println();
}
System.out.println("-------------------------------");
for(String str : methods.keySet())
{
System.out.println(str);
for(String methodName : methods.get(str))
{
System.out.print(methodName + " ");
}
System.out.println();
}
The yielded result was like so:
so.B
c
so.SO
b c a
so.A
b
-------------------------------
so.B
getC
so.SO
fooMethod3 getData fooMethod1 fooMethod2 main
Which should be what you are after.

Calling a method with an argument trough reflection

I have the following code which allows me to input in the scanner the Employee getter method that I want to call and it will do it using reflection (the name of the method should not appear anywhere in the code). This works for getter methods but I now need to modify the code to do something similar for setter methods. I have been trying to figure how to do it for the past week but I have been unable. Any help would be appreciated.
Thanks.
public static void main(String[] args) {
Employee e = Employee.testEmployee(); // a sample employee
Class cls = e.getClass();
Scanner scanner = new Scanner (System.in); // to parse data the user types in
String nextCommand;
// until the user enters "quit", get the next input from the user, and if it matches
// a given command, get the desired information from the employee object
do {
System.out.print("Enter command >> ");
nextCommand = scanner.next();
Method method = null;
try{
method = cls.getMethod(nextCommand);
}
catch(NoSuchMethodException x) {
}
try{
System.out.println(method.invoke(e));
}
catch(IllegalAccessException x) {
}
catch(java.lang.reflect.InvocationTargetException x) {
}
catch(NullPointerException x) {
}
} while (! nextCommand.equals("quit"));
}
Here's a code sample that does what you want to achieve:
public class Test {
private static HashSet<Class<?>> classes = new HashSet<>();
static {
classes.add(String.class);
classes.add(Integer.class);
classes.add(GregorianCalendar.class);
}
public static void main(String[] args) throws NoSuchMethodException,
SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
X obj = new X();
obj.setField("lala");
Method method = obj.getClass().getMethod("getField", null);
System.out.println(method.invoke(obj, null));
Method setMethod = getWorkingMethod(obj);
setMethod.invoke(obj, "who let the dogs out");
System.out.println(obj.getField());
}
private static Method getWorkingMethod(Object obj) {
Method method = null;
for (Class<?> c : classes) {
try {
method = obj.getClass().getMethod("setField", c);
} catch (NoSuchMethodException | SecurityException e) {
continue;
}
if(method != null){
return method;
}
}
throw new IllegalArgumentException("No such method found!");
}
}
class X {
private String stringField;
public void setField(String s) {
stringField = s;
}
public String getField() {
return stringField;
}
}
Output:
lala
who let the dogs out
Notes:
Create a collection (I used a HashSet) that stores Class<?> objects. You will use these to iterate over the possibilities and see if a method with that argument exists.
Use a try-catch to see if the method exists (an exception is thrown when it can't find it).
This will not work for overloaded methods. If this is your scenario, you'll have to make adjustments. I expect it to be no problem though, since you said this was meant for setters (which typically don't have overloads).
You can avoid calling the getter and setter methods by directly accessing the Field through reflection.
The Field object has various get and set methods that can be used to manipulate field values.
See: http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getField%28java.lang.String%29
EXAMPLE
import java.lang.reflect.Field;
public class MyObject {
private String fieldA;
public String getFieldA() {
return fieldA;
}
public void setFieldA(String fieldA) {
this.fieldA = fieldA;
}
public static void main(String[] args) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
MyObject myObject = new MyObject();
myObject.setFieldA("Test");
Class clazz = myObject.getClass();
Field field = clazz.getDeclaredField("fieldA");
field.setAccessible(true);
String fieldA = (String) field.get(myObject);
System.out.println(fieldA);
field.set(myObject, "Test2");
fieldA = (String) field.get(myObject);
System.out.println(fieldA);
field.setAccessible(false); //be sure to return field to private
}
}
Resolution (method or field resolution) in java slows down you execution time by 'orders of 10 or 100', hence not a smart design decision. So, resolve once at start time, cache method instance, and execute it from cache. Avoid frequent lookups using reflection.

Decorator in Java

I see about decorator example in Python:
def makebold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped
def makeitalic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped
#makebold
#makeitalic
def hello():
return "hello world"
print hello() ## returns <b><i>hello world</i></b>
And got some curious how it can be implement in Java, so I search and got some example using Decorator Design Pattern.
public class Main {
public static void main(String[] args) {
Wrapper word = new BoldWrapper(new ItalicWrapper());
// display <b><i>hello world</i></b>
System.out.println(word.make("Hello World"));
}
}
public interface Wrapper {
public String make(String str);
}
public class BoldWrapper implements Wrapper {
private Wrapper wrapper;
public BoldWrapper() {
}
public BoldWrapper(Wrapper wrapper) {
this.wrapper = wrapper;
}
#Override
public String make(String str) {
if(wrapper != null) {
str = wrapper.make(str);
}
return "<b>" + str + "</b>";
}
}
public class ItalicWrapper implements Wrapper {
private Wrapper wrapper;
public ItalicWrapper() {
}
public ItalicWrapper(Wrapper wrapper) {
this.wrapper = wrapper;
}
#Override
public String make(String str) {
if(wrapper != null) {
str = wrapper.make(str);
}
return "<i>" + str + "</i>";
}
}
How do I make this like the Python example above using a Java Annotation like this one:
public class Main {
public static void main(String[] args) {
#BoldWrapper
#ItalicWrapper
String str = "Hello World";
// Display <b><i>Hello World</i></b>
}
}
public #interface BoldWrapper {
public void wrap() default "<b>" + str + "</b>";
}
public #interface ItalicWrapper {
public void wrap() default "<i>" + str + "</i>";
}
I got some problem when I tried to make the sample, the problem is I don't know how I can pass the str value from the main method to the BoldWrapper and ItalicWrapper so it can concatenate and how to return it, so the main method can display the result that has been concatenate.
Please advise if there is something wrong with my understanding of annotation.
If you are particularly interested in doing this kind of stuff with annotations (you don't have to really):
This example should get you started:
public class AnnotationTest
{
#Target( ElementType.METHOD )
#Retention( RetentionPolicy.RUNTIME )
public static #interface TagWrapper
{
public String[] value() default {};
}
public static interface TextFragment
{
public String getText();
}
public static class TagWrapperProcessor
{
public static String getWrapperTextFragment( TextFragment fragment )
{
try
{
Method getText = fragment.getClass().getMethod( "getText" );
TagWrapper tagWrapper = getText.getAnnotation( TagWrapper.class );
String formatString = "<%s>%s</%s>";
String result = ( String ) getText.invoke( fragment );
for ( String tag : tagWrapper.value() )
{
result = String.format( formatString, tag, result, tag );
}
return result;
}
catch ( Exception e )
{
throw new RuntimeException( e );
}
}
}
public static class BoldItalicFragment implements TextFragment
{
private String _text;
public BoldItalicFragment( String text )
{
_text = text;
}
#Override
#TagWrapper(
{
"b", "i"
} )
public String getText()
{
return _text;
}
}
#Test
public void testStuff()
{
System.out.println( TagWrapperProcessor.getWrapperTextFragment( new BoldItalicFragment( "Hello, World!" ) ) ); // prints: <i><b>Hello, World!</b></i>
}
}
This is late but I think it may help the other people. From Java 8 with Function interface, we can write something close to python decorator like this:
Function<Function<String, String>, Function<String, String>> makebold = func -> input -> "<b>" + func.apply(input) + "</b>";
Function<Function<String, String>, Function<String, String>> makeitalic = func -> input -> "<i>" + func.apply(input) + "</i>";
Function<String, String> helloWorld = input -> "hello world";
System.out.println(makebold.apply(makeitalic.apply(helloWorld)).apply("")); // <b><i>hello world</i></b>
1) The link you cited is a good one - it does justice to the "Decorator Pattern" with respect to Java. "Design Patterns" themselves, of course, are independent of any particular OO language:
http://en.wikipedia.org/wiki/Design_Patterns
2) Here is another good link:
When to use the decorator pattern
In Java, a classical example of the decorator pattern is the Java I/O Streams implementation.
FileReader frdr = new FileReader(filename);
LineNumberReader lrdr = new LineNumberReader(frdr);
4) So yes, the "decorator pattern" is a good candidate for this problem.
Personally, I would prefer this kind of solution:
String myHtml =
new BoldText (
new ItalicText (
new HtmlText ("See spot run")));
5) However annotations are also an option. For example:
http://docs.oracle.com/javase/1.5.0/docs/guide/language/annotations.html
Python decorators very like java annotation, but that are very different principle.
Annotations, a form of metadata, provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate.
But you can prosessing class file with bytecode enhancement. I make a simple project for implementing that approach. It using javassist processing class file after building. It searching methods with specified annotation in classes. And add bridge methods for calling between wrapped method and original method. It look like, calling bridgeMethod() -> wrapperMethod() -> originalMethod(). Your can reference from https://github.com/eshizhan/funcwraps.
Although this doesn't resolve how to use annotations as you wanted, rather than using the "decorator design", I could propose you use the "builder design" if it suits better to your needs (it seems like so).
Quick usage example:
public class BuilderPatternExample {
public static void main(String args[]) {
//Creating object using Builder pattern in java
Cake whiteCake = new Cake.Builder()
.sugar(1)
.butter(0.5)
.eggs(2)
.vanilla(2)
.flour(1.5)
.bakingPowder(0.75)
.milk(0.5)
.build();
//Cake is ready to eat :)
System.out.println(whiteCake);
}
}
Output:
Cake{sugar=0.75, butter=0.5, eggs=2, vanila=2, flour=1.5, bakingpowder=0.0, milk=0.5, cherry=0}
For full implementation and a very good explanation, please check
http://javarevisited.blogspot.mx/2012/06/builder-design-pattern-in-java-example.html

java enum receive values from string name

I have enum like:
public enum Enum2
{
ONE,TWO,THREE;
}
I can list all values like:
public static void main(String... args)
{
for (Enum2 e : Enum2.values())
{
System.out.println(e);
}
}
Is it possible list values if I have only string name of Enum?
String enum_name="Enum2";
E.g. if in some logic like:
if (a>b)
{
enum_name="EnumA";
}
else
{
enum_name="EnumB";
}
And after I receive string name of enum - I can list all values.
Class<?> enumClazz = Class.forName("com.mycompany.Enum2");
for (Enum<?> e : ((Class<? extends Enum<?>>)enumClazz).getEnumConstants()) {
System.out.println(e.name()); // The variable "e" would be Enum2.ONE, etc
}
Thank you #Harry for helping me get this right.
Your question is not much clear to be but this is what you may want to do
Class<?> cls = Class.forName("EnumName");
if (cls.isEnum()) {
Field[] flds = cls.getDeclaredFields();
//-- your logic for fields.
}
You can use: Class.getEnumConstants(). For more see this.
yes, with
Enum2.EnumA.toString();

Categories

Resources