Reflection versus container configurations [duplicate] - java

This question already has answers here:
If reflection in Java slows down execution by orders, why do so many frameworks use it ?
(2 answers)
Closed 7 years ago.
Using reflection in Java is very expensive because it affects performance very badly right.But I wonder that , reflection is widely used in container configurations (web.xml),frame works like Structs,REST.. , and ORM like hibernate etc.
How it can be justified?Is it because reflection used only once when container is up or some other reason behind it?

There is no other way for them to do what they do (a good example of this might be Spring framework - it doesn't force you to use any interface when using dependency injection, and since it has no interface to use and doesn't know your classes at compile time, the only way is to inspect them via reflection)
The reflection-heavy parts are not (should not) be executed too often
Reflection isn't that very expensive if done right (e.g. if you only lookup the method you want to call once and then cache the java.lang.reflect.Method object found and use it in further invocations)

First, I wouldn't say that using reflection has such a detrimental effect on code performance. Of course, there is an overhead, but there are optimisation techniques in place, that make sure that the performance impact is kept to a minimum. As far as the trade - off between performance and usability is concerned, the specific requirements of the product being developer should be taken into account. For example, would I use a heavy reflection - based framework on mobile - I think not. Does it makes sense on the backend - I would say yes.
Second, having annotation based configuration doesn't always mean that there is reflection used at application runtime. There are frameworks that make use of the AnnotationProcessor framework and generate java code during compilation, which is later used as "normal code". Also, a lot of frameworks use annotation configuration in conjunction with byte - code generation at runtime, so basically, reflection is kept at a minimum.

Related

Understanding Java reflection drawbacks

I am trying to understand the drawbacks as mentioned in Java docs
Security Restrictions
Reflection requires a runtime permission which may not be present when
running under a security manager.
What are the runtime permissions that reflection needs? What is security manager in this context? Is this drawback specific to Applets only?
Exposure of Internals
Since reflection allows code to perform operations that would be
illegal in non-reflective code, such as accessing private fields and
methods, the use of reflection can result in unexpected side-effects,
which may render code dysfunctional and may destroy portability.
Reflective code breaks abstractions and therefore may change behavior
with upgrades of the platform.
How reflection can break abstraction? and how does it affect with upgrades of the platform.
Please help me in clarifying these. Thanks a lot.
First you should always ask to yourself why reflection in your code. Aren't you able to do the operations without reflection. If YES then only you should use reflection. Reflection uses meta information about class,variables and methods this increase overhead, performance issue and security threat.
To understand the drawback of reflection in detail visit http://modernpathshala.com/Forum/Thread/Interview/310/what-are-the-drawbacks-of-reflection
Security "sandboxes" aren't limited to applets. Many other environments which permit less-than-completely-trusted "plug-in" code -- webservers, IDEs, and so on -- limit what the plug-ins can do to protect themselves from errors in the plug-in (not to mention deliberately malicious code).
A framework class called dependency container was used to analyzes the dependencies of a class. With this analysis, it was able to create an instance of the class and inject the objects into the defined dependencies via Java Reflections. This eliminated the hard dependencies. That way the class could be tested in isolation, ex. by using mock objects. This was Dagger 1.
Main disadvantages of this process were two folds. First, the Reflection is slowing itself and second, it used to perform dependency resolution at runtime, leading to unexpected crashes.

Annotating REST web service in Java EE 6

I am making a web service with Java EE 6. From what I understand you can annotate either the local interface with the #Path/#GET etc. annotations or the no-interface bean. I wonder if it is common to make two interfaces; one for the web services with the annotations and another one for the local interface? Or do you just add them on the local interface?
If I understand your question, your asking if you should define an interface just for specifying the annotations. I'm not sure what the advantages would be of doing this, unless you had a really complex project and foresee yourself replacing the Web service annotations with another library. This library would have to be on its virtual deathbed in terms of future support, or there would need to be clear evidence that our CTO would be changing technologies for me to consider this strategy.
For most projects, this seems to be somewhat of an overkill, especially if you already have an interface defined for your controller that you can add those annotations to. As a colleague on your project, I wouldn't want to have to check 3 different files for annotations for 1 class, unless there was a very compelling reason to do so.
With that said, if you wanted to add the annotations to your interface or your subclass, this is supported in this example. However, I think you would want to be sure to create a clear standard, either all your REST annotations are on the interface or all of your annotations are on the subclass. Mixing and matching them could get confusing for someone new to the project.
Without actually seeing your code and how complex it is, I can't tell you which method would be best for your project. The important thing is to balance consistency with flexibility. In summary, Java gives you plenty of rope, which equals flexibility, but you can also hang yourself with that rope if you're not careful. :)

Why is the Spring framework called "non-intrusive"?

Spring framework is NON - INTRUSIVE.
Can you please elaborate this?
Thank You :)
Here, "non-intrusive" means that your application code doesn't need to depend on the Spring framework directly. Anything that can inject the appropriate dependencies will (theoretically) work just as well.
The main appeal of a nonintrusive framework is that it stays out of the way of your design and modelling activities. It stays completely out of the way until you need it.
It is perfectly possible to use Spring without any direct dependencies on the spring framework in your application code. That doesn't mean the code will continue to function without spring, since the functionality provided by spring will need to be replaced by another IoC container or code which directly instantiates all objects in a dependency chain, but it does mean that you can choose to wire things up with spring, or via some other mechanism.
However, to be really unintrusive with spring, you need to keep all of your configuration outside of your code, which means using XML for everything. This works beautifully in spring, but its a pain in the neck for developers and, since the advent of the widespread use of annotations in Java 5, isn't really the java way. So spring provides lots of annotations for wiring things together directly in your code. This can obviously create dependencies on Spring within the code, although all of the Spring tags are resolved at compile time, so you can still execute your classes outside of a spring context without any dependencies on spring jars and such. Also, wherever possible, custom spring annotations have been replaced with generic JEE annotations. With Spring 3, it is really pretty easy to use only JEE annotations plus a limited quantity of XML to initialize the application context.
The beauty of the spring way of doing things is that the underlying functionality which implements a feature can often be selected at runtime. If you are using an ORM system in a non-managed container for development, using a native session manager, you can easily switch to container managed sessions in production without changing any code whatsoever if you have configured the app to let spring handle transaction management. Methods that are marked as #Transactional will pick up a session and transaction automatically, regardless of the source, without any changes to the code. In fact, you can trivially switch to an entirely different ORM framework, if you are so inclined, though that's a pretty rare use case, in truth, so most applications will tend to have ORM framework specific code and/or queries in their data access code.
The difference between spring and an old-fashioned 'intrusive' framework is that intrusive frameworks often require you to implement particular interfaces or, even worse, force you to inherit from particular base classes, in order to access framework functionality. In the latter case, not only do you have a dependency on the framework you are using, but it severely limits your class hierarchy structure, too - in a language which only allows single inheritance. Recent versions of EJB learned from the elegance of Spring's (and others') less-intrusive model and EJB itself has since become much less intrusive (It's all about the POJOs).
I don't really see any support for irreputable's argument that spring is now a billion dollar beast that locks users in. Spring is, if anything, less intrusive than it has ever been while offering ever more functionality. It is certainly possible to lock yourself into spring, and a lot of devs are perfectly willing to do so precisely because the runtime overhead of using spring is so trivially small that most of us can't imagine a lot of scenarios in which we might remove spring from a project. If I want a fully managed JEE environment, I can configure for that (and run in the container of any available vendor). If I want to run in tomcat or jetty with 100% of configuration and runtime management coming from spring, I can do that, too. So I'm generally perfectly happy to use spring-specific functionality at the risk of lock-in unless the project requirements specifically forbid it. Spring adds very little overhead at runtime, so it is a low risk choice.
When push comes to shove, I find Spring to be far easier to learn than EJB. I can accomplish the same things with either methodology, but it is easier to bring in devs who are inexperienced if I'm using Spring compared to EJB, so hiring is easier, long term maintenance costs are lower, and release cycles are shorter.
No matter what the language direction, generally speaking, a framework is too intrusive, which is a voice of criticism, so I guess it is not because of this that non intrusiveness has become a "selling point" of publicity.
For example, spring and struts 2 use annotations, configuration files, conventions or reflection (other languages may be other ways) to achieve non-invasive, and the compilation and operation does not have formal dependence on the framework API.
But in essence, without this framework, our program simply cannot run correctly. These so-called annotations are customized. When and how they are processed are different. Think about the migration from gson to Jackson. The migration has costs and risks. Do you need users to write a new one?
In addition, how high is the probability of real migration? It feels very small.
years ago, there was this EJB beast, which was very "intrusive". Spring was touted to be a much simpler set of helper classes, and it was more like libraries than frameworks.
today, Spring becomes the new beast. As a billion dollar business, it is in their best interest to lock people in. Yeah, sure, you don't have a dependency problem, and you can quit Spring anytime.
With EJB, at least you have a few vendors to choose from.

developing a simple orm [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I want to develop a simple orm which performs CRUD functionality.Shold i use reflection?
does libs like hibernate use reflection??
does using reflection will cause the speeed to drop down by a large extent?
Yes Hibernate uses reflection and annotations (or XML configuration files), but it will only index and read all meta information once (at startup). I would recommend though to look at the existing ORM solutions first before you start rolling your own.
A simple ORM is DAO (Data Access Object). You can specify your CRUD operations very well.
For More ORM patterns or Methodology, read Martin Fowler's book: Patterns of Enterprise Application Architecture
Also, you can use the existing JPA (Java Persistence API) and write your own JPA.
Reflection, dynamic proxies, cglib, asm, javassit - all are used in ORM tools.
But, you really don't want to create a new one. Because you can't create a simple ORM. ORMs aren't simple to create and you will realize it once you reach a certain point. So don't waste your time. Use an existing one. There are plenty, some more complicated, some less complicated (and less powerful).
You can google for "simple ORM" and you will have plenty of choices that are (more or less) easy to use. (But not to implement)
Well, not so long ago, I wrote an ORM layer for GAE named gaedo. This framework is modular enough to also fit relational databases. Hopefully, it was my third attempt at such a job. So, here are what is needed and why.
Reflection is the root of all ORM mapping tools, since it'll allow you to explore classes looking for their attributes names and values. This is a first use. It will also allow you to load values from your datastore, provided your bean has a convenient constructor (usually, ORM frameworks rely upon Java Beans, since these beans ensure a no-arg constructor exists). Finally, reflection will allow you to load values from datastore in beans, which is, i think, the most important thing. Unfortunately, you'll fast be faced with the issue of the query that loads the whole database, which will require you the two newt steps
Considering graph loading, you'll fast need to rely upon dynamic proxies to create lazy loadable objects. Obviously, if you rely solely upon JDK, you will only able to use that on objects implementing well-known interfaces (as an example, collections and maps are very good examples of objects benefiting from dynamic proxies implementing their interface).
Finally, annotations will be of smaller use. They'll allow you to define key elements (used to generate the database key for an object, as an example), define parent-children relationships, or even define lazy-loading strategy, in association with previously mentioned dynamic proxies.
This is an interesting, but mostly useless, research effort. Interesting, because it will learn you tons of concepts regarding reflection, proxies, and all those things people ignore and tend to consider as reserved to so-called dynamic languages.
But useless, because you'll always encounter corner cases requiring you hacking your code.
As Emmanuel Bernard told in "Les castcodeurs" (a french Java podcast), I think, each year, someone come with a "reimplementation" of Hibernate. And each year, this implementation reveals itself lacking some important fragments, like transaction, local or distributed, cache handling, ...
So, try to code it, and never forget it can be dropped soon due to a too great overlap with installed frameworks.
To answer the last part of your question, yes; reflection is a serious performance hit. All the work that you normally have the compiler to you instead have to do at run time, so use reflection sparingly (cache classes for example so you only create them once, preferably at startup).
I haven't looked through Hibernate's code, but I expect it uses reflection as well, but as optimized as possible.
My recommendation is that you write a working dead-simple solution first, then start optimizing as you go along.
Try JLibs-JDBC.
This is simple ORM which doesn't use reflection or xml configuration

A good Design-by-Contract library for Java? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
A few years ago, I did a survey of DbC packages for Java, and I wasn't wholly satisfied with any of them. Unfortunately I didn't keep good notes on my findings, and I assume things have changed. Would anybody care to compare and contrast different DbC packages for Java?
There is a nice overview on
WikiPedia about Design by Contract, at the end there is a section regarding languages with third party support libraries, which includes a nice serie of Java libraries. Most of these Java libraries are based on Java Assertions.
In the case you only need Precondition Checking there is also a lightweight Validate Method Arguments solution, at SourceForge under Java Argument Validation (Plain Java implementation).
Depending on your problem, maybe the OVal framework, for field/property Constraints validation is a good choice. This framework lets you place the Constraints in all kind of different forms (Annotations, POJO, XML). Create customer constraints through POJO or scripting languages (JavaScript, Groovy, BeanShell, OGNL, MVEL). And it also party implements Programming by Contract.
Google has a open source library called contracts for java.
Contracts for Java is our new open source tool. Preconditions,
postconditions, and invariants are added as Java boolean expressions
inside annotations. By default these do nothing, but enabled via a JVM
argument, they’re checked at runtime.
• #Requires, #Ensures, #ThrowEnsures and #Invariant specify contracts as Java boolean expressions
• Contracts are inherited from both interfaces and classes and can be selectively enabled at runtime
contracts for java.
I tested contract4J one time and found it usable but not perfect.
You are creating contracts for for and after method calls and invars over the whole class.
The contract is created as an assertion for the method. The Problem is that the contract itself is written in a string so you don't have IDE support for the contracts or compile time cheching if the contract still works.
A link to the library
It's been a long time since I've looked at these, but found some old links. One was for JASS.
The other one that I had used (and liked) was iContract by Reliable Systems. It had an ant task that you would run as a preprocessor. However, I can't seem to find it with some google searches, it looks like it has vanished. The original site is now a link farm. Check out this link for some possible ways to get to it.
I'd highly recommend you to consider the Java Modeling Language (JML).
There is a Groovy extensions that enables Design by Contract(tm) in Groovy/Java code - GContracts. It uses so-called closure annotations to specify class invariants, pre- and postconditions. Examples can be found on the project's github wiki.
Major advantage: it is only a single jar without external dependencies and it can be resolved via Maven compliant repositories since its been placed in the central Maven repo.
If you want a plain and simple basic support for expressing your contracts, have a look on valid4j (found on Maven Central as org.valid4j:valid4j). It lets you express your contracts using regular hamcrest-matchers in plain code (no annotations, nor comments).
For preconditions and postconditions (basically assertions -> throwing AssertionError):
import static org.valid4j.Assertive.*;
require(inputList, hasSize(greaterThan(0)));
...
ensure(result, lessThan(4.0));
If you are not happy with the default global policy (throwing AssertionError), valid4j provides a customization mechanism that let's you provide your own implementation of org.valid4j.AssertiveProvider.
Links:
http://www.valid4j.org/
https://github.com/helsing/valid4j
I would suggest a combination of a few tools:
Java's assert condition... or it's more advanced Groovy cousin, Guava's Preconditions.checkXXXX(condition...) and Verify.verify(condition...), or a library like AssertJ, if all you need is just to do simple checks in your 'main' or 'test' code
you'll get more features with a tool like OVal; it can check both objects as well as method arguments and results, you can also fire checks manually (eg to show validation errors on UI before a method is called). It can understand existing annotations eg from JPA or javax.validation (like #NotNull, #Pattern, #Column), or you can write inline constraints like #Pre(expr="x >= 0 && x <= y"). If the annotation is #Documented, the checks will be also visible in Javadocs (you don't have to describe them there as well).
OVal uses reflection, which can make performance issues and other problems in some environments like Android; then you should consider tool like Google's Cofoja, which has less functionality, but depends on compile-time Annotation Processing Tool instead of reflection
I think that many DbC libraries were surclassed by the builtin assert keyword, introduced since Java 1.4:
it is a built-in, no other library is required
it works with inheritance
you can activate/deactivate on package basis
easy to refactoring (e.g. no assertions in comments)
I personally think that the DbC libraries available at present have left a lot to be desired, none of the libraries i looked at played well with the Bean Validation API.
The libraries i looked at have been documented here
The Bean Validation API has a lot of over lap with the concepts from DbC. In certain cases Bean Validation API cannot be used like simple POJO's (non CDI managed code). IMO a think wrapper around the Bean Validation API should suffice.
I found that the existing libraries are a little tricky to add into existing web projects given that they are implemented either via AOP or Byte code instrumentation. Probably with the advent of Bean Validation API this kind of complexity to implement DbC is unwarranted.
I have also documented my rant in this post and hope to build a small library which leverages on the Bean Validation API

Categories