Unwrapping classes enhanced by Guice AOP - java

Is there an "official" way to "unwrap" (i.e., obtain the non-enhanced class) for classes enhanced by Guice AOP?
So far, I detect these classes by looking for the string "$$EnhancerByGuice$$" in the class name and - if it is present - reverting to the superclass (Guice AOP works on classes using inheritance).
I'd prefer something that does not break when Guice decides to change this suffix string (which is by no means part of any API or contract).

As far as I can tell, there is no official way. There is an issue open to address it but given the prioritization I doubt it will happen. In the meantime, if you want to avoid breaking when Guice decide to change the suffix string, add a unit test that proves you can detect an enhanced class.

Related

Extending classes without overriding anything: Bad practice?

I'm taking over an old project. Now I have some classes in the flavor of own util class overriding a util class of external library. E.g.:
public final class StringUtilsXXX extends org.apache.commons.lang3.StringUtils {
}
These classes are not overriding any methods of the extended class at all (and never will be in the future). I find it confusing, that most calls on the own implementation are just delegating to the super class. Is this bad practice?
Yes. This is bad practice. The argument for why is that it tightly couples your own classes to a third party library. I'm sure the reason your predecessor did this, is so that if he needed to some day replace commons-lang, he would only have to change one piece of the code. He probably did this because of frustration from upgrading from lang2 to lang3.
The way he should have done this, would have been to create a StringUtil interface, and write different implementations of this (you could have a StringUtil which was implemented using lang2, one that used lang3 and even maybe a fallback implementation that was implemented from scratch. (if you needed some string handling not provided by either, or if you needed to compile some versions with an older Java version, or whatever).
Normally not needed if you are not overriding anything or adding any data or method member in subclass. However, for future placeholder, this may be used.
It will not hurt for now. But using (has a) StringUtils should be preferred over extending it, if no additional behavior is provided.
If there is an interface available for StringUtils and you are pointing your implementation (extending class instance using it) then it might still make some sense from maintainability point of view (that again depends on how you are instantiating it).
I don't consider it as a bad practice necessarily. There are cases that you may not want to rely on the API of an external library, and you might want to build a wrapper layer between the client (your) code and the external library. The reason doing this would be that you have control of the API of the wrapper contrary to the API of the external library.
I guess what he really did, from the pattern standpoint, is a decorator. I don't know anything about this particular library (because I'm a .net dev) and does it expose interfaces that he should implement instead but I would rephrase the question to:
Is it fine to create decorators on 3rd party libraries or should we make adapters instead.
As far as I see it, adapters are the right answer. But there is something more that puzzles me here: shouldn't we always try as hard as we can not to break contract when upgrading our project we give away to others? Did "they" have to introduce new namespace?
If they did, should we blame our colleges for hacking code to maintain project despite someone else's doubtful ideas/solutions?
No.. This is a bad practice. Suppose tomorrow org.apache.commons.lang3.StringUtils changes something (removes a method. Though it is unlikely, it can still happen with other classes especially with custom classes), imagine the impact it would have on your code. You are actually tightly coupling your methods with org.apache.commons.lang3.StringUtils.

working of Java Annotations

I want to know, if I've got it correct or not. I've been reading about annotations and wanted to know how all the magic happened. Here's what I think happens. Please let know if otherwise.
Firstly, let's take some annotation. Say AssertTrue. Now, the specs of the annotation is provided in javax.validation.constraints. Now, as such, AssertTrue does not really do anything. i.e. if I were to do the following
public class MyClass{
#AssertTrue(message = "MyMessage")
public myMethod(){
//something
}
}
Now, this particular piece of code is not going to do anything but save the metadata info that on this method myMethod I have some additional info i.e. message and annotation. How I make use of this info is upto me.
This is where the hibernate-validator framework comes into picture.
What it does is, that it provides a bunch of classes and it takes in the object that is supposed to be validated. On that object, it will check if AssertTrue annotation is there. If found, it will invoke the method isValid that is provided in the implementation of the AssertTrueImpl.
Is this what is happening?
Also, I have a few questions. say I have my own custom annotation and I want to provide a framework that checks something. For the sake of argument, let's say I want to do what the hibernate-validator is doing. Now how does one go about it?
Also, when the JVM encounters some annotation, what happens behind the scene? Does it look for some implementation? What exactly does it look for?
i.e. what will JVM do if it encountered AssertTrue in my code. Surely it does not have to do much but store some information, and it does not have to go looking for any implementation too, since whenever I call validator.validate() that's when it will look for hibernate-validator implementation.
let me know if I have understood it correctly.
You are correct. The annotation by itself does nothing, it's just metadata that may be used by a processing tool. In this case, Hibernate validator.
The usual procedure for those tools is to scan on the classpath what classes have metadata that they can use to build or enhance a class (by injecting a proxy, or registering an interceptor, or any other kind of operation). They either do scan the classpath, or an external configuration mechanism (xml, json, annotations on a config class [Spring way]) specifies this for the framework so that it knows where to look for annotated classes.
And so, you too, can benefit from annotations on your project, following the same discovery method. In fact, if you happen to work with CDI, you will probably use them a lot. They're quite useful for bean interception, or for providing metadata on your classes that would otherwise have to be treated with a lot of boilerplate code.
I encourage you to use them profusely.
Cheers!
You understand annotations correctly - they are just metadata on specific members (fields, methods, classes, ...). Some of them are intended for compile time only, some of them are intended for runtime. The latter will be available via Reflection API (basically forming additional metadata on annotated members). There are numerous possibilities of what you can do with this feature, where declarative validation defined by JSR-303 (and implemented by Hibernate Validator) is just one of them.

How to detect JavaBean class has changed (isDirty)

I am looking for an efficient (code-wise, and runtime-wise) means to identify whether a JavaBean object has changed.
I was thinking of holding a clone of the class that could be compared on demand to the class instance. This is similar to the strategy used by CSLA.net.
The question is, is there already a means to achieve this using native JRE JavaBeans, or with the addition of some library (Apache commons BeanUtils?) or, even by adding the constraint of JEE6 EJB's.
Ideas and theories both welcome...
bean-properties might have something helpful (although it's not JavaBean strictly speaking). Otherwise you can add a call to a notifyPropertyChanged(..) method from each setter - it's ugly, though.

How to write annotations using multiple enum types?

I'm attempting to write some annotations to help associatate test case methods with various metadata. My annotations so far include BugFix, UseCase, and Requirement. My end goal is to write an annotations processor to display which test cases are associated with individual bug fixes, use cases, and requirements.
When I was just implementing this for my own project, I created enums specific for my project for each test association category. For example, I had ProjectUseCase enums, which I could pass as the value to the UseCase annotation on my test methods. This made it easy to add additional use cases or modify use cases in a single place.
Now, I'd like to make this code available for other developers at my work. Of course, they will be working on other projects, with different use cases, requirements, and bug fixes.
Here are the problems I'm running into:
Enum cannot be extended, so I cannot have a base UseCase enum which others can extend for their own projects.
Values for annotation properties have to be constants. This prevents me from using an interface marker (TestAssociation) on my enums, and using the TestAssociation interface for the values of my annotation. Also, this prevents me from using String values in my annotation, and passing in the enum name when I use the annotation, such as: #UseCase(ProjectUseCase.GENERAL.name()).
From what I can tell, this leaves me with just using raw Strings for the values, which deprives me of type safety and the ability to quickly refactor. Using classes of constant Strings in place of the enums seems to be the best way to handle this, as every developer can use their own.
The only other thing I can think of is to reference an Enum class (or a class of constant Strings), and not include the class in the jar, leaving it for the users to implement.
Any suggestions or workarounds?
I'd also like to know if there are any projects out there already providing similar functionality.
Yup.
The only good way out of this is to allow for arbitrary user-defined annotations, so that if my enum is FooEnum, I can define FooAnnotation that uses it. Your framework can recognize FooAnnotation as being the annotation it's looking for by seeing whether it itself is meta-annotated with #UseCase (or whatever you please)!

Java Annotations

What is the purpose of annotations in Java? I have this fuzzy idea of them as somewhere in between a comment and actual code. Do they affect the program at run time?
What are their typical usages?
Are they unique to Java? Is there a C++ equivalent?
Annotations are primarily used by code that is inspecting other code. They are often used for modifying (i.e. decorating or wrapping) existing classes at run-time to change their behavior. Frameworks such as JUnit and Hibernate use annotations to minimize the amount of code you need to write yourself to use the frameworks.
Oracle has a good explanation of the concept and its meaning in Java on their site.
Also, are they unique to Java, is there a C++ equivalent?
No, but VB and C# have attributes which are the same thing.
Their use is quite diverse. One typical Java example, #Override has no effect on the code but it can be used by the compiler to generate a warning (or error) if the decorated method doesn't actually override another method. Similarly, methods can be marked obsolete.
Then there's reflection. When you reflect a type of a class in your code, you can access the attributes and act according to the information found there. I don't know any examples in Java but in .NET this is used by the compiler to generate (de)serialization information for classes, determine the memory layout of structures and declare function imports from legacy libraries (among others). They also control how the IDE form designer works.
/EDIT: Attributes on classes are comparable to tag interfaces (like Serializable in Java). However, the .NET coding guidelines say not to use tag interfaces. Also, they only work on class level, not on method level.
Anders gives a good summary, and here's an example of a JUnit annotation
#Test(expected=IOException.class)
public void flatfileMissing() throws IOException {
readFlatFile("testfiles"+separator+"flatfile_doesnotexist.dat");
}
Here the #Test annotation is telling JUnit that the flatfileMissing method is a test that should be executed and that the expected result is a thrown IOException. Thus, when you run your tests, this method will be called and the test will pass or fail based on whether an IOException is thrown.
Java also has the Annotation Processing Tool (apt) where not only you create annotations, but decide also how do these annotations work on the source code.
Here is an introduction.
To see some cool stuff you can do with Annotations, check out my JavaBean annotations and annotation processor.
They're great for generating code, adding extra validations during your build, and I've also been using them for an error message framework (not yet published -- need to clear with the bosses...).
The first thing a newcomer to annotations will ask about annotations is: "What is an annotation?" It turns out that there is no answer to this question, in the sense that there is no common behavior which is present in all of the various kinds of java annotations. There is, in other words, nothing that binds them together into an abstract conceptual group other than the fact that they all start with an "#" symbol.
For example, there is the #Override annotation, which tells the compiler to check that this member function overrides one in the parent class. There is the #Target annotation, which is used to specify what kinds of objects a user defined annotation (a third type of construct with nothing in common with other kinds of annotation) can be attached to. These have nothing to do with one another except for starting with an # symbol.
Basically, what appears to have happened is that some committee responsible for maintaining the java language definition is gatekeeping the addition of new keywords to the java language, and therefore other developers are doing an end run around that by calling new keywords "annotations". And that's why it is hard to understand, in general what an annotation is: because there is no common feature linking all annotations that could be used to put them in a conceptual group. In other words, annotations as a concept do not exist.
Therefore I would recommend studying the behavior of every different kind of annotation individually, and do not expect understanding one kind of annotation to tell you anything about the others.
Many of the other answers to this question assume the user is asking about user defined annotations specifically, which are one kind of annotation that defines a set of integers or strings or other data, static to the class or method or variable they are attached to, that can be queried at compile time or run time. Sadly, there is no marker that distinguishes this kind of annotation from other kinds like #interface that do different things.
By literal definition an annotation adds notes to an element. Likewise, Java annotations are tags that we insert into source code for providing more information about the code. Java annotations associate information with the annotated program element. Beside Java annotations Java programs have copious amounts of informal documentation that typically is contained within comments in the source code file. But, Java annotations are different from comments they annotate the program elements directly using annotation types to describe the form of the annotations. Java Annotations present the information in a standard and structured way so that it could be used amenably by processing tools.
When do you use Java's #Override annotation and why?
The link refers to a question on when one should use the override annotation(#override)..
This might help understand the concept of annotation better.Check out.
Annotations when it comes to EJB is known as choosing Implicit middle-ware approach over an explicit middle-ware approach , when you use annotation you're customizing what you exactly need from the API
for example you need to call transaction method for a bank transfer :
without using annotation :
the code will be
transfer(Account account1, Account account2, long amount)
{
// 1: Call middleware API to perform a security check
// 2: Call middleware API to start a transaction
// 3: Call middleware API to load rows from the database
// 4: Subtract the balance from one account, add to the other
// 5: Call middleware API to store rows in the database
// 6: Call middleware API to end the transaction
}
while using Annotation your code contains no cumbersome API calls to use the middle-
ware services. The code is clean and focused on business logic
transfer(Account account1, Account account2, long amount)
{
// 1: Subtract the balance from one account, add to the other
}

Categories