Dynamic Java Variable Naming - java

This question is more for furthering my knowledge than anything...
Does Java have anything similar to PHP's ability to generate a variable name? I have an SCJA Cert and I'm studying for the SCJP and have never seen this, but was curious.
PHP Example
$application->{$request->getParameter("methodCall")}($request->getParameter('value'));
Does Java have anything similar? I've been reading on here and the general answer is to use a HashMap which I'm not interested in since this isn't to solve a real problem. I'm more interested in the is this possible solution? If not so be it, but just trying to expand my knowledge!
Thanks,
Jared

No, variables (fields and local variables) are statically "created" at compile-time in Java.
Of course memory is only ever occupied at runtime, but how many and which fields an object has is decided at compile-time.
Therefore you can't "dynamically add a field" in Java.
And yes: A Map is the solution to the problem. "Adding a field" is not usually the problem but an attempted solution that's appropriate for some languages (usually dynamic ones) and inappropriate for others.

I think you mean a field in a class. A local variable can only be used in a method.
To generate a field in a class or a variable, you need to generate Java code and compile it or byte code at runtime. It can be done but is 100x more complicated than using a simple Map. (I have done it dynamically before and I wouldn't recommend it unless you really have to)
If you want to do code generation I would suggest using Objectweb's ASM.

This can't be done...Java Reflection only allows you to view the structure of a class but not append to it.

Related

Is using Java Reflection Bad Practice?

I am building an application for a client and I am in the situation where I need to have the ability to reference a field value via a string, i.e the users uses a string to define which field they want to change the value of, this is part of an abstract framework so technically I don't know the name of the fields they desire to change. Of course I could do this using hash maps, but I am considering using java reflection as this allows the fields to stay as fields of the object rather than the values being coded into a hash map. I have used reflection for my own personal work, but I was wondering if using Java reflection is actually bad practice, and I should stick to the hashmap methodology.
(Any other suggestions for solving the design problem described are also appreciated)
Thanks
The question itself is opinion based, although I believe most will agree that you can't just say "reflection is bad". Sometimes it's the only way, which is why a lot of libraries use reflection. Sometimes it's not the only way, but a workaround would be even worse. Sometimes it's not the only way, and not the easiest way, but the developer is far too amazed at the power of reflection to think straight.
Except for that last one there are plenty of valid reasons to consider reflection as a solution.
Personally reflection makes me sad, and in my experience there is almost always a better way. In the problem you described, setting variables based on a string i'd consider going with your hashmap idea which would reference variables via a string key which seems like exactly what you are describing. If you need the ability to reference values that do not exist you could also include factory methods to create variables when no key exists and then add to the map, if you are wrapping the objects then they will be passed by reference to avoid the problem you describe but this depends on the implementation (eg using Integer class etc for auto boxing if you are referencing primitives) Together this would allow for a much tighter and well defined implementation rather than reflecting values here there and everywhere. Apologies for the anti-reflection bias! Hope this helps.

Can you dynamically rename a class name?

Is it possible in Java to give a class or even its functions a new name at run time. By reading in the new names as arguments or on a configuration file when the program is started?
UPDATE:
Here is the purpose of this. I am using Java Script Engine to allow any JSR 223 compatible Scripting Language to access our API. Some of our clients are not used to using Java and it's naming conventions and would feel more comfortable using their own specific naming conventions. So I am required to give them the capability to dynamically change the API's class and function names without actually changing them in the code. It was suggested I use a Map and some sort of binding with a string name and the actual Java name e.g.,
map.put("Hello",HelloWorld.class)
Object obj = new Hello();
which should be the same as,
Object obj = new HelloWorld();
If this is not possible please tell me why. I need a solid Java expertise answer. This is out of my league and I need facts to tell people why this is not possible even though myself I am almost sure it's not possible.
Possible Solution:
Here is the closets solution I have come up with. Using this link,
https://weblogs.java.net/blog/2005/08/10/reflection-and-dynamically-changing-classes
I could add in the names at run time, use composition to create an Adapter Class, and then compile the file, and voila the Script Language folks could use their defined names instead of my API's Java names.
Is this the only conceivable way to accomplish this?
UPDATE 2:
Here is another possible solution for anyone trying this too,
http://asm.ow2.org/doc/faq.html
That'll take you directly to their frequently asked questions which will have one for this exact problem.
No, you will need to refactor for references and recompile for execution.
Yes, you are able to do that using javassist.
In particular, you have to edit NewExpr.

Using reflection to modify the structure of an object

From wikipedia:
reflection is the ability of a computer program to examine and modify the structure and behavior (specifically the values, meta-data, properties and functions) of an object at runtime.
Can anyone give me a concrete example of modifying the structure of an object? I'm aware of the following example.
Object foo = Class.forName("complete.classpath.and.Foo").newInstance();
Method m = foo.getClass().getDeclaredMethod("hello", new Class<?>[0]);
m.invoke(foo);
Other ways to get the class and examine structures. But the questions is how modify is done?
Just an additional hint since the previous answers and comments answer the question concerning reflection.
To really change the structur of a class and therefore its behaviour during runtime look at Byte code instrumentaion and in this case javassist and asm libs. In any case this is not trivial task.
Additionally you might have a look at aspect programming technic, which enables you to enhance methods with some functionallity. Often used to introduce logging without the need to have a dependency of the logging classes within your class and also dont have the invocations of the logging methods between the problem related code.
In English reflection means "mirror image".
So I'd disagree with the Wikipedia definition. For me, reflection is about runtime inspection of code, not manipulation.
In java, you can modify the bytecode at runtime using byte code manipulation. One well known library and in wide spread use is CGLIB.
In java, reflection is not fully supported as defined by the wikipedia.
Only Field.setAccessible(true) or Method.setAccessible(true) really modifies a class, and still it only changes security, not behaviour.
Frameworks like e.g. hibernate use this to add behaviour to a class by e.g. generating a subclass in bytecode that accesses private fields in the parent class.
Java is still a static typed language, unlike javascript where you can change any behaviour at runtime.
The only method in reflection (java.lang.reflect) to modify object's class behaviour is to change the accessibility flag of Constructor, Method and Field - setAccessible, whatever wiki says. Though there are libraries like http://ru.wikipedia.org/wiki/Byte_Code_Engineering_Library for decomposing, modifying, and recomposing binary Java classes

Need to get my hands dirty on reflection

I have read about Java Reflections but till date it has been a vague concept to me. Can someone give a brief details with short example on how to use reflections in Java ?
Thanks.
I have read about Java Reflections but
till date it has been a vague concept
to me.
Here is a quick into to reflection in java:
Structural introspection. Basic reflection deals with the introspection of object at run-time. This means that you can learn the structure of objects and classes at run-time programmatically, e.g. get the class of the object, list the methods of the class, list the fields defined in the class, etc.
Reflective invocation and instantiation. With reflection you can invoke a method at run-time which is not defined at compile-time, e.g. invoke method named M on object O, where M is read in a configuration file. You can also instantiate object dynamically without knowing the class at compile-time.
Annotations. Then you can move one level up in the meta levels, and play with annotations. Annotations describe other elements such as class, method and fields. Many framework rely on this.
Dynamic proxy. Dynamic proxy can be generated at run-time. In this case, it's really like if you create a class dynamically at run-time. To use with care, but definitively handy and powerful in some cases.
I guess you will start with structural introspection. There are links to tutorials in the other answers, but I hope this gives you an overview of what else can be done.
I guess the article 'Using Java Reflection' found on sun.com might be a good starting point.
It's primarily to be used to access classes/methods/fields programmatically (i.e. during runtime instead of compiletime). Good real world API's which uses reflection intensively are ORM's like Hibernate/JPA.
You can find here a Sun tutorial on the subject (click Next link at the bottom to paginate through it).
Something worth mentioning as well is Javassist. Not only does it have reflective abilities, but it also allows run-time bytecode manipulation using ordinary source syntax! Once you've gotten into reflection a bit more (which you probably have by now), you'll truly appreciate it's beauty.

It's possible in Java to access the source code of a method "reflectively"?

I'm afraid that the answer is no, but maybe one of you surprises me.
Thanks.
Edit 1:
I'm aware that the question doesn't make much sense but I think the point was understood and, sadly, the answer is no. Anyway I changed the title of the question adding quotes to the word "reflectively" and I will try to better explain my intentions just in case.
I have a instance of a type which is a subclass of some abstract type which has some known methods. I want to get, at runtime, a String with the source code of the actual implementation of one of such methods in the instance type.
I think it's worth pointing out that the actual type of the instance may be an anonimous inner class....
Also that a "decompiled" version of the source code it's good enough. The method I want to get the source, most of the time, has only one line....
Thanks.
As other's pointed out: no.
You can access objects of a class, its methods etc. the way the JVM can. This is only possible because every class stores information about itself and its members when being compiled.
If I had to guess, this happens in Object, the rootobject in the inheritance tree. You may decompile the class file using a decompiler and use that one for examination. But you cannot access the sourcecode like a String or anything similar.
Think about it: If you have scala-code compiled for JVM, you cannot get the scala-code back either. And you cannot get java-code.
Is there any special reason you want to do this? May there be any other way you could try to achieve your goal, whatever it might be?
regards
I don't think so. When the .java is compiled it becomes a .class; as far as I know Java doesn't have a built-in decompiler to turn that .class back into a .java. All that a runnable application knows about is .class files.
No you can't. Its a little illogical as well.

Categories