Using annotation for an object sorter? - java

I am working a container to hold a list of objects (of the same class) the have certain fields that use a custom RetentionSortable annotation. The purpose of the annotation is two fold:
To mark the field as able to be compared to another objects same field.
And to give the sort name of the field (eg. Modification Date or First Name).
The container will then walk through the list of objects (remember they are like) and gather the list of RententionSortable's that the object contains and pass the list to the GUI. The GUI will display the list and request a sortable selection and return it to the sortable which will then sort the list based on the RetentionSortable selected.
The purpose of this method or sorting object is to allow me to create a small container that can generically accept any object and sort it as long as it has at least one RetentionSortable field.
My gut screams that this is bad practice and that relying this much on reflection is a bad idea but my tests work flawlessly and better than I expected.
Is using annotation reflection to find all the fields that are annotated by a particular annotation good practice for abstract object sorting?

Annotations are there for convenience, and your use is making the situation more convenient, so it seems reasonable. The alternative is to maintain a separate dictionary of which fields are sortable for which objects, and is slightly more cumbersome but slightly better from a seperation of concerns point of view.
The question is really whether your object should know about the annotations or not (is the object going to be reused in another situation where the annotations do not make sense or conflict). With a separate list of sortable fields, you can pick which to apply in any given case.
If the convenience trade-off works for you, then you should stick with the annotations, just so long as you are aware of the potential design ramifications (which may be nothing for your particular case).

How do you think basically every annotation-driven configuration framework works? "Give me all the of such-and-such type fields annotated with '#Inject'" or "give me everything in package baz.plugh annotated with '#Controller'".
Whether or not it's good for "abstract sorting" or not, I don't see why not. If it works, and eliminates the need for things like bean mappers and bean info classes, what's the issue?

Related

Java Object Clone (additional class member) using Prototype, Builder Pattern

It is not easy to explain my issue.
JPA creates some complex objects for calculations, which are stored in a database.
We decided to set the results in a working copy of this objects.
This means for each object model we created a seperated working copy model file with the same fields but some other LocalDates values and new result fields.
When the calculation was starting the working copies are instantiated.
This approach is not the best i think.
I think of the prototype pattern to clone the object.
There i come to the problem how to add the new fields. How?
Instantion costs and ist creates lots of additionals model class files.
I only think of put the result field in the calculation data models as transient fields.
Maybe inner class or local class?
I also tried to use an interface as data bucket.
But thats not the realy purpose of interfaces and also it works only with many curious trick.
For Unit Tests and user input i think it is the best to use the builder pattern and then tell JPA to store the parent object, or not?
Sorry but my answer was to long for a comment :(
There is big complex object relationship with Lists and Sets One To Many etc. relationship. When i set the result i a new class i cant determine the right object e.g. in a list. So we bild the same structurefor these result and seperated these classes in a package. Maybe it is possible to dont build the structure a second time with also references to the "basic classes". It should be sufficient to reference to each basic class a result class. It would only a little bit more navigation to get values from deeper classes. For a similiar use case there must be a best practise, or? Interfaces or sth. I very dislike the many classes for the result. Is it not possible to clone and add classmember to it for the result or to logical group easier or something like this?
It could be a solution for somebody:
http://help.eclipse.org/luna/index.jsp?topic=%2Forg.eclipse.jdt.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fjdt%2Fcore%2FIWorkingCopy.html
Here you will work with the Eclipse API and create IWorkingCopies.
For the described task toooo much.

How should one use abstracted instances

I am designing a game and I have good overview of what I am doing.
However I've been trying to improve my OOP skills but now and then I face the same problem, how should I use the abstracted objects?
Lets say I have a list of Entitys that represents anything that has x and y property on screen and probably width and height haven't figured all out yet!
Then I have special types of entitys, one that can move and one that cannot and probably something like collidable in future.
They're all in a collection of Entitys (List<Entity> in my case) and now I want to simulate entitys that moves and are instances of DynamicEntity on main loop but they're all on abstract list of Entitys and I don't know is the Entity in loop either dynamic entity or not.
I know I could just check it with instanceof but I am pretty sure that's not the best idea..
I've seen some people having something like boolean inside the Entity for checking its type but I don't really want to hardcode all kind of entitys there..
I just want to know what is the best practice in such case?
Usually it's better to avoid checking the type if possible. If you think you need to use instanceof in your code then there's probably an abstraction you could be using to make your design more extensible. (If you decide to add a third type of Entity in the future you don't want to have to go back and update all of your instanceof checks with a third case.)
There are two common ways to have different actions based on an instance's concrete type without checking the concrete type:
One common way is the visitor pattern. The idea here is to create a Visitor class with an action for each type of object. Next, each concrete class has an accept method which simply calls the correct visit method inside the visitor class. This single level of indirection allows the objects to choose the correct action themselves rather than you choosing it by checking the type.
The visitor pattern is usually used for one of two reasons. 1) You can add new actions to a class hierarchy that implements the visitor pattern without access to the classes' source code. You only have to implement a new visitor class and use it in tandem with the visitable classes' pre-existing accept methods. 2) When there are many possible actions one can perform on classes from some type hierarchy sometimes it's more clear to split each action off into it's own visitor class rather than polluting the target classes with a bunch of methods for a bunch of different actions, so you group them with the visitor rather than the target classes.
However, in most cases it's easier to do things the second way: to simply override the definition of a common method in each concrete class. The Entity class might have an abstract draw() method, then each type of Entity would implement that draw() method in a different way. You know that each type of Entity has a draw() method that you can call, but you don't have to know the details of which type of entity it is or what the method's implementation does. All you have to do is iterate over your List<Entity> and call draw() on each one, then they'll perform the correct actions themselves depending on their type since each type has its own specialized draw() implementation.
You're right that you don't want to check the instance type or have some sort of function to check capability. My first question would be - why do you have a list of entities of that base type in the first place ? It sounds to me like you need to maintain a list of dynamic entities.
You could implement a move() method that does nothing for non-dynamic entities, but again that doesn't seem right in this particular scenario.
Perhaps it would be better to implement an event that triggers the iteration of that list, and pass that event into each object in turn. The dynamic entities could decide to move upon that event. The static entities would obviously not.
e.g.
Event ev = ...
foreach(e : entities) {
e.actUpon(ev);
}
In this scenario you could have different event types, and the entities would decide upon their action upon the basis of the event type and the entity type. This is known as double-dispatch or the visitor pattern.
If your processing of entities relies on knowing details about the entity types, then your Entity abstraction doesn't buy you much (at least not in this use-case): your List<Entity> is almost as opaque for you as a mere List<Object>.
If you know that every entity you can imagine will be either static or dynamic, there's no "hard-coding" in having a boolean property to all entities: isDynamic() or something.
However, if the dynamic aspect only makes sense for a subset of your entities, this flag will indeed bring some mess to your abstraction. In this case, my first guess is that you didn't model the use-case properly since you need to work with a list of items that do not provide enough polymorphic information for you to handle them.

How to use reflection to retrieve private variable property from JPA objects

One of my goals is to create an engine that will set values in pojo object from JPA objects dynamically using reflection. One of the matching criteria is, that the field names should match.
I was successfully able to implement this for two pojo objects. But when I tried using JPA objects as one of the object parameter, it didn't work. Based on my research I found out that the method Class.getDeclaredFields() , does not give me the name of the field but the getter/setter method name of member variable for JPA objects.
Can anyone please give me a lead or direction as in where/what should I look to accomplish this task?
JPA providers will often use dynamic proxy classes of your concrete JPA classes, so you have no guarantee of the field names in the proxy. The only guarantee about a proxy is that the methods are the same. Use a debugger to inspect the runtime class of the JPA class instances that you're trying to use and you'll see the problem.
The best you'll be able to do is use reflection to call methods on JPA-returned objects.
All that aside, I don't really see why you'd need to POJO-ify an entity class anyway, since an entity is primarily an annotated... POJO.
One of the matching criteria is, that the field names should match.
I think that this is the root of your problem. There is simply no guarantee that a Java object's field names will match the names of getters and setters ... or anything else. If you make this assumption, you will run into cases where is doesn't work.
The best solution is to simply not use this approach. Make it a requirement that the Pojo classes conform to the JavaBeans spec and rely on the setters to set the properties. This is likely to work more often than making assumptions about (private) field names.
In fact, the state of a generic JPA object implemented using a dynamic proxies could well be held in a hash map. Those fields you can see could simply be constants used for something else.

Structural design pattern

I'm working with three separate classes: Group, Segment and Field. Each group is a collection of one or more segments, and each segment is a collection of one or more fields. There are different types of fields that subclass the Field base class. There are also different types of segments that are all subclasses of the Segment base class. The subclasses define the types of fields expected in the segment. In any segment, some of the fields defined must have values inputted, while some can be left out. I'm not sure where to store this metadata (whether a given field in a segment is optional or mandatory.)
What is the most clean way to store this metadata?
I'm not sure you are giving enough information about the complete application to get the best answer. However here are some possible approaches:
Define an isValid() method in your base class, which by default returns true. In your subclasses, you can code specific logic for each Segment or FieldType to return false if any requirements are missing. If you want to report an error message to say which fields are missing, you could add a List argument to the isValid method to allow each type to report the list of missing values.
Use Annotations (as AlexR said above).
The benefit of the above 2 approaches is that meta data is within the code, tied directly to the objects that require it. The disadvantage is that if you want to change the required fields, you will need to update the code and deploy a new build.
If you need something which can be changed on the fly, then Gangus suggestion of Xml is a good start, because your application could reload the Xml definition at run-time and produce different validation results.
I think, the best placement for such data will be normal XML file. And for work with such data the best structure will be also XMLDOM with XPATH. Work with classes will be too complicated.
Since java 5 is released this kind of metadata can be stored using annotations. Define your own annotation #MandatoryField and mark all mandatory fields with it. Then you can discover object field-by-field using reflection and check whether not initiated fields are mandatory and throw exception in this case.

java Annotation reflection

I have a java class, for some field (not all field), I will put an annotation for the filed. Now, I would like to find all the fields which have annotation?
I know, I can iterate all fields, and find whether the field has annotation.
Since there is only one or two field has annotation, so I would like a quick method to find such annotated field.
I don't know any way quicker than iterating over all the fields. Given that anything else would require some other piece of code to iterate over all the fields first and store the annotations in a form more optimized for your use case - which certainly won't be useful for all annotations - I wouldn't expect there to be anything provided for you.
Have you benchmarked the speed of just iterating over the fields, and found it too slow? If you only need to do this occasionally, it's probably fast enough as it is. If you need to do it multiple times on the same class, then you can create a cache for this yourself, so you only ever need to iterate over the fields of any particular class once.

Categories