A lot of Java projects use reflection. I wonder if is there a reflection library which make the use of java.lang.reflect easier.
We could use it like:
Reflected object = new Reflected( new Object() {
String name="Oscar";
String lastName="Reyes";
String reverseName(){
return new StringBuilder(name+lastName)
.reverse()
.toString();
}
int nameLength() {
return (name+lastName).length();
}
});
String name = object.getString("name");
object.set("name", "Mr. Oscar");
String reversed = ( String ) object.exec("reverseName");
int count = ( Integer ) object.exec("nameLength");
....
UnknownLibraryObject reflectionMadeEasy
= new UnknownLibraryObject( .... );// initialize with an object from somewhere
String someString = ( String ) reflectionMadeEasy.get("stringPropertyFromTheReflectedObject");
int someInteger = ( String ) reflectionMadeEady.execute("someMethodFromReflectedObject", 1,2,3 );// with args.
Do every project that use reflection start from the scratch or is there a library already for this?
It's not clear what you're trying to do, but Apache Commons Lang provides a number of convenient utilities classes to make reflection a bit less cumbersome, such as MethodUtils, FieldUtils and ConstructorUtils. These typically provide one-liners to abstract out the often bulky raw reflection code.
As #Lauri pointed out, Commons BeanUtils is also available, providing more high-level functions, such as copying properties between objects.
See also java.beans.Expression and java.beans.Statement.
Apache Commons Lang is as straight forward as it gets. There is also Whitebox which is PowerMock's Reflection Helper - here is the Quick Summary from the wiki.
Quick summary
Use Whitebox.setInternalState(..) to
set a private member of an instance or
class.
Use
Whitebox.getInternalState(..) to get a
private member of an instance or
class.
Use Whitebox.invokeMethod(..)
to invoke a private method of an
instance or class.
Use
Whitebox.invokeConstructor(..) to
create an instance of a class with a
private constructor.
I like it better than ACL as you don't have to be explicit with the staticness of the Fields and Methods.
Most convenient is jOOR, with it your code becomes:
Reflect.on(anyObject).field("stringPropertyFromTheReflectedObject").get()
Reflect.on(anyObject).call("someMethodFromReflectedObject", 1,2,3).get()
Spring Framework contains some helpers, not all that different from Commons Lang/BeanUtils ...
http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/util/ReflectionUtils.html
http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/beans/BeanUtils.html
Both classes are marked as 'intended for internal use', but still worth a look.
You may even find that you're really looking for a framework such as Spring to manage your objects ... hth
I don't know, but if you find yourself using the standard Java reflection APIs a lot, maybe there is something not quite right about the way you design and implement Java programs.
Java is primarily designed as a staticly typed language, and works very well when used that way. While dynamic typing and (particularly) reflection can get you out of difficult problems, it is generally a good idea to restrict their use because:
they reduces performance,
they makes your source code more complex and less readable, and
they make your code more fragile.
Hiding the reflection behind a library layer or within a Sping-like framework addresses the readability issue but not the performance or fragility issues. (There are other approaches that do address all of the issues ... but without more information about why you are doing so much reflective programming, it is not clear they are relevant.)
For Spring Framework users. There are some utility classes to work with the reflection easier:
org.springframework.util.ReflectionUtils
org.springframework.util.ClassUtils
org.springframework.core.annotation.AnnotationUtils
org.springframework.util.TypeUtils
Related
I am fairly new to using Python as a OOP. I am coming from a Java background. How would you write a javabean equivalent in python? Basically, I need a class that:
Implements serializable.
Has getters and setters -> private properties
dummy constructor
Any inputs? I am looking for a sample code!
You don't, because Python is not Java. Most likely you should just write a less trivial class, construct a namedtuple, pass a dictionary, or something like that. But to answer the question:
Neither serializable nor "implementing an interface" makes sense in Python (well, in some frameworks and advanced use cases it does, but not here). Serialization modules, such as pickle, work without implementing or inheriting anything special (you can customize the process in other ways, but you almost never need to).
You don't write getters and setters. You just use public attributes. Should you later require a nontrivial getter/setter, you can turn it into a property transparently.
There's no need for a dummy constructor, unless you want to create the attributes and set default values for them. But that's probably a bad idea (for a bean-ish class), as not assigning values to those attributes is most likely an error, and dubious even when it isn't. So just let Python catch those errors for you (it raises AttributeError when a non-existent attribute is accessed).
Well, I'd think that data classes would be similar to Java beans and that using them is actually a good idea, as it removes boiler plate.
You can serialize most object via the pickle module;
There are no such things as private attributes in Python (see also:
Does python have 'private' variables in classes?,
Actual implementation of private variables in python class);
Classes that do not define a constructor will use a default (according to the method resolution order).
Example for constructor 'chain':
>>> class A(object):
... def __init__(self):
... print("A")
...
...
>>> class B(A): pass # has no explicit contructor
...
>>> b = B()
A
>>>
And - as #delnan wrote - you might want to read: http://dirtsimple.org/2004/12/python-is-not-java.html -- Java and Python have quite different cultures, it takes some time to dive into (and appreciate) both.
Also, after writing some code, it might be helpful to compare it to common idioms, as listed here (I certainly learned a lot this way):
http://www.jeffknupp.com/blog/2012/10/04/writing-idiomatic-python/
http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html
http://python3porting.com/improving.html
Implements serializable.
Pick your favorite format, and write a function that will serialize it for you. JSON, Pickle, YAML, any work. Just decide!
Has getters and setters -> private properties
We don't do that here, those are attributes of bondage languages, we are all adults in this language.
dummy constructor
Again not something we really worry about as our constructors are a little bit smarter than other languages. So you can just define one __init__ and it can do all your initialization, if you must then write a factory or subclass it.
As pointed by miku:
Objects can be serialized by picke module, but there is not an interface to be implemented, Python is not Java.
There is no private attribute in python, usually people use bar (the underscore) to mean private attributes, but they can be accessed from external world. Getters and setters are waste of time of both CPU and programmers.
Nothing to add to miku answer.
about properties: Real world example about how to use property feature in python?
good text: http://dirtsimple.org/2004/12/python-is-not-java.html
How are templated methods implemented in C++?
I'm thinking about implementing templates in the JVM and have got a possible implementation thought out for templated classes, but am unsure on methods.
If, for example, you did:
class Test
{
public static boolean isIterable<T>(T variable)
{
return T instanceof Iterable;
}
}
System.out.println(Test.isIterable(new int[] { 0 }));
Would I create a version of Test that replied to int[]? (In my implementation, the class would be named as such: $g$Test$A_Java_lang_int)
Please ignore any problems with generics (such as only requiring boxed objects), as I intend to remove them.
I plan on creating these resolved templates dynamically, and keeping track of the number of references so I can remove them if they are not used. I believe this is how .Net manages it, although I'd be happy to be wrong here!
Would I create a version of Test that replied to int[]?
Essentially, yes. Templates in C++ are purely a compile-time mechanism that uses a (glorified) macro mechanism to generate code based on a template for each type with which it’s instantiated.
(C++ actually does a lot more due to the possibility of specialisation but this is the gist of it.)
I would suggest trying to do this staticly by generating the classes. You might find http://trove.starlight-systems.com/ interesting as it has a templating approach to generating its primitive collections. e.g. TintLongHashMap This doesn't rely on any language features.
I would suggest you work out how to do this staticly before trying to do it dynamicly which is much harder.
I found that there seem to be 2 general solutions:
don't obfuscate what is referred to through the reflection API [Retroguard, Jobfuscate]
replace Strings in reflection API invocations with the obfuscated name.
Those solutions work only for calls within the same project - client code (in another project) may not use the reflection API to access non-public API methods.
In the case of 2 it also only works when the Reflection API is used with Strings known at compile-time (private methods testing?). In those cases dp4j also offers a solution injecting the reflection code after obfuscation.
Reading Proguard FAQ I wondered if 2 otherwise always worked when it says:
ProGuard automatically handles
constructs like
Class.forName("SomeClass") and
SomeClass.class. The referenced
classes are preserved in the shrinking
phase, and the string arguments are
properly replaced in the obfuscation
phase.
With variable string arguments, it's generally not possible to determine
their possible values.
Q: what does the statement in bold mean? Any examples?
With variable string arguments, it's generally not possible to determine their possible values.
public Class loadIt(String clsName) throws ClassNotFoundException {
return Class.forName(clsName);
}
basically if you pass a non-constant string to Class.forName, there's generally no way for proguard or any obfuscation tool to figure out what class you are talking about, and thus can't automatically adjust the code for you.
The Zelix KlassMaster Java obfuscator can automatically handle all Reflection API calls. It has a function called AutoReflection which uses an "encrypted old name" to "obfuscated name" lookup table.
However, it again can only work for calls within the same obfuscated project.
See http://www.zelix.com/klassmaster/docs/tutorials/autoReflectionTutorial.html.
It means that this:
String className;
if (Math.random() <= 0.5) className = "ca.simpatico.Foo";
else className = "ca.simpatico.Bar";
Class cl = Class.forName(className);
Won't work after obfuscation. ProGuard doesn't do a deep enough dataflow analysis to see that the class name which gets loaded came from those two string literals.
Really, your only plausible option is to decide which classes, interfaces, and methods should be accessible through reflection, and then not obfuscate those. You're effectively defining a strange kind of API to clients - one which will only be accessed reflectively.
I have 2 questions that I was hoping someone could help me with. Is there a way to create a class on the fly with android/java and also add variables to the class? For example I would like to do something like this:
Class c = new Class();
c.name = 'testing';
c.count = 0;
c.getName = new function(){
return c.name;
}
Just wondering if this is possible or if there is another way to do this. Basically I want to build an object that I can use the data from as an object.
No, the syntax you describe is not possible in Java. I'm not sure what you are trying to accomplish there. If you want to create a class to use to hold data on the fly, you can create an anoynmous inner class.
Object object = new Object() {
private String name = testing;
private int count = 0;
public String getName() {
return name;
}
}
In general, I wouldn't use this for a data objects though. This functionality is typically used for anonymous implementations of interfaces to support callbacks, etc.
This is not typically done. It can be done by reflection, but would be a fairly bad idea--This type of code is really annoying to debug, won't interact correctly in the IDE (For instance, ctrl-clicking on an instance of c.getName wouldn't be able to jump to where the method is defined), it would probably be a pretty big performance hit, etc.
However, for some generic tools this is possible. I believe Hibernate might have the ability to create classes from DB tables.
The most common use, however, is in mocking used within testing frameworks--They can do almost exactly what you want. Look at EasyMock with TestNG.
In general, though, you are better off just defining a business class and going with it rather than trying to make some abstract framework that generates your classes for you.
Static utility methods are generally frowned up by OO purists.
I was wondering however what people feel about utility methods that are used to avoid something simple like a null check throughout the application.
String.trim() throws a NPE when invoked on a null String. So I have to do:
if(str!=null)
setValue(str.trim());
else
setValue("");
What if I create a utility method that checks for the null?
setValue(myTrim(str));
public static String myTrim(String str) {
if(str==null) return ""
else return str.trim();
}
The one problem I have encountered with methods like these is that some developers on the team might not like/not know this utility and might be doing staight calls after doing a null comparison.
Is this something that you do your framework too? If yes, what are the other common utility general use methods that people have created and are using in their applications?
What do you feel are the pros and cons of either approach?
I'd be inclined to replace the homegrown uses when an existing library (like Apache Commons Blah Blah Blah) already has written it. Code you can offload to someone else lets you focus on the important parts of the software that truly differentiate your work from everyone else's. But yes, utility classes with static methods are great, if they need to be written by you at all.
FYI, take a look at StringUtils.trimToEmpty(). Good luck.
some developers on the team might not like/not know this utility
That's what communication is good for. And I don't mean e-mail.
Talks about these kind of functions, probably other team members are doing the same and by not communitating you're duplicating code and efforts.
You may find a way to use these utility methods or even some more experienced developer migth have already develop a more mature lib or used a 3rd party.
But by all means, communicate with your team
I'm not an OO purist. So i love stuff like this. Anything that makes it easier to write code that reflects my intentions without getting bogged down in irrelevant details.
Write it. Use it yourself. Don't be shy - demonstrate how much cleaner it makes your code. Worst case, at least there'll be a bit less repetition in your code...
In terms of a design principle, there are some things that are just more logically static methods. If the utility class that you're writing doesn't really have any "state", and it feels more logical to make it uninstantiable with a bunch of static methods, then do it like that. But make sure your class is genuinely uninstantiable (give it a private constructor; I've seen people declare the class as abstract, but that's no good because people can override it).
The problem that you then get into is that if your class is project-wide, you need to treat it as a library class. And writing libraries is different from writing general code:
in general code, you should profile rather than prematurely optimising; but in a library method, you can't predict how people will use your call in the future;
you need to be very careful to document or clearly name what your method does;
you need to give it generic behaviour, and not be blinded by some specific feature that you need at that moment (e.g. if you have a method to "tokenise a string", what do you do with empty tokens? if you need to ignore them, will other callers to your method?)
I have a few classes that just contain fave static methods - they do make sense to have. You can put together extensive unit tests checking any and all boundary conditions.
In the case you described though - wouldn't it be better to make the setValue method accept any string sent to it? The method could then apply a default null string, trim it or even throw an exception if the value was incorrect.
The JavaDoc on that routine can then clearly state what inputs are valid/invalid and what happens to invalid inputs.
Not saying this is right - just another viewpoint
I use a lot of utility functions. There are some things that just don't need "objects", but I don't like the particular example you have of trim().
A reference to string that is null is very different from an empty string. Unless the app is very simple, and you know you always want to read a null reference as "", I wouldn't do it. For this case, I prefer:
setValue((str != null) ? str.trim() : "")
For me, an uncaught NPE is a good indication that there's a major error going on in the application!