Is it possible to implement/override an abstract method with reflection? - java

I have a question about Reflection, but the motivation is from using Spring Framework.
Consider this project, which is a sort of Minimum Working Example version of a deployed project.
In the ProjectionResourceProcessorConfig class, I have an entityProjectionResourceProcessor method for every projection, and every entity in the database have a few projections. That's about 60 methods.
I don't want to keep this up because of the obvious maintenance disadvantage. I want to use Reflection in order to automatically register one bean for every projection class.
The postProcessBeanDefinitionRegistry method in the ProjectionResourceProcessorConfig class shows that I can get the list of classes I want to use to register one bean for each and shows how to register a bean programatically.
However, because I need to use the ProjectionResourceProcessor class, I need to override the getEntityClass method. I haven't been able to find a way to do that programatically. That's why I've declared the inner class. It shows the programatic bean registration working, but it falls in the same issue as requiring a piece of code for every bean.
Apart from reflection, I tried to use the setMethodOverrides method of the RootBeanDefinition class to override that method, but I couldn't manage to understand how to use that method. Google couldn't find any documentation or usage example (except for a vaguely related Chinese post with copies on several different websites).
I also tried to use the MethodReplacer class but I haven't found how to use it with annotation driven configuration.
I also tried to replace the getEntityClass method by a variable and replace the variable's value by reflection, but apparently when the variable is read the value that was set in the super class is the one that is retrieved.
To test the project, run the tests at DemoApplicationTests. It will print the projection of some entities. If they have links, it's working.
Is it possible to do what I want? If it is, how?
Thanks in advance.

Related

Find all calls to interface implementers?

There are a large number of classes in this codebase which use a specific interface. However, picking a few at random, I've been unable to find one which is actually called anywhere; as such, I don't have a great idea of how to use it.
Is there a way in Eclipse to find every instance of any class which implements this interface?
In other words, suppose there exists an interface Interface, and classes ClassA, ClassB, ClassC, ..., ClassX, which all implement it. I want to see every point in the code where something like `ClassX obj = new ClassX(). Most of the classes I'm finding that implement this interface don't have any point where they're actually used; I assume they're for future use.
Open the interface class, hold Control and move your mouse to interface's name, select open implementation. That's the simplest and easiest way to do.
Yes, highlight the interface name and hit F4 or right click -> Open type hierarchy.
Update after OP's edit:
If you are using a framework that uses dependency injection like spring probably you don't find any reference because some of the implementations are defined in a xml file.
Also consider if some implementations are created and invoked via reflection.
Some classes might be loaded during runtime e.g. using reflection. To catch-them-all you can set a method entry breakpoint on the interface method. This is explained in this answer. That way all calls to implementation methods will suspend the JVM regardless of what is the object type.
Do note that unlike the line breakpoints the method breakpoints will really slow down the performance of the JVM.

How to understand annotation in java And How to implement my annotation in java?

What I have known are:
annotation was added in java 5
annotation can be using in method, class, and property
annotation can work in RUNTIME, CLASS, SOURCE( I don't know how to work with CLASS and SOURCE, and their's features)
annotation with retention which is RUNTIME can be implement when java program is running.
And I want to implement a annotation to have follows features:
ensure class only being allowed to create a instance
ensure methods only being allowed to access method in the class
it is like as friend in c++
it is same as public and private , but more dynamicall, like
#MyAnnotation(allowMethods={xxx.doSomething})
public void getValue(){}
the getValues method only can be accessed in the instance self and xxx.doSomething() method
What should I do and learn in next?
And Where can I learn about these?
I think you might be misunderstanding something there. Annotations are descriptive elements, not parts of your program. You can write as many annotations as you want, and people who use your code will still be able to ignore them.
That said, an annotation that enforces a policy (as yours does) can actually be implemented, either at compile or at runtime, but you need an external mechanism to help you. I can think of 3:
Annotation processing lets you interact with the compiler and process annotations by generating code or by omitting compiler errors. Unfortunately, I don't think it will work for your case, as you want to protect your annotated type from instantiation, and that means the call site doesn't actually have an annotation. Annotation processing only gives you access to the actual code pieces that have annotations, not to those that refer to them.
AspectJ allows you to write policy enforcement aspects and omit compiler errors, based on static pointcuts. The problem here is that static pointcuts have very limited semantics, so while you could forbid the instantiation of your class altogether, or from certain packages, you could not limit the your class instantiations to 1.
The third way, and probably the only sane way is that you use a container like Spring or Guice and configure your class as singleton. As long as you only retrieve your class from the container, it will never create a second instance.
Finally: If you want to limit the number of instantiations of your class, you can always use a classic Singleton pattern approach.

What is the difference between autowiring and object creation?

What is the difference, if I autowire a class and provide value and instantiate an object of class and provide some value?
For example-
#Autowired
private UserService userService;
userService.findUser(userName, password);
And
User user = new user();
userService.findUser(user.getuserName(),user.getpassword());
What is the difference in Autowiring and sending the data and instantiating the object and sending the data to some service class?
I'm trying to clarify the concepts in spring.
When you use #Autowired you are leaving it up to the Spring framework to find and instantiate the userService. This is usually controlled through some configuration file or some other configuration, which allows you to change the behaviour of your application without changing the code itself.
On the other hand, when you instantiate the object yourself, you are specifying which object you are after and what type of class you want. This could leave you with less ambiguous code since you know what type of object is being initialized, but to make a change in your application's behaviour you would need to change your code.
In essence, the first option is less coupled than the second option, which is usually the recommended way of building things.
Your example doesn't make a lot of sense; this User class, which looks like some plain data object, isn't adding anything to the second snippet.
The idea of "autowiring" is that some class, like maybe a Web controller, will need a UserService in order to get its work done. When Spring autowires the UserService, it goes into the context and finds a matching object and provides it to the class that needs it. This is technically separate from creating the object.
That said, the best practice is to use constructor injection--simply declare the other objects you need as constructor parameters and annotate the constructor with #Autowired (or #Inject). Spring will know to look up all the dependencies you need and call the constructor with them. This means that it's also very simple to provide mocks of those objects for testing or development.
Well, the main difference is that in case u use #Autowired the object is also created, however, it's created by container and container decide when to do that.
I want to give you a simple example:
You have four classes 1,2,3 and 4. Three of them (1,2,3) uses the 4th. So, if you use new(), it`s hard to decide where to create object(in class 1, or 2, or 3, or even in each of them) of 4th class. Moreover, later you can delete class with object initialization and other 2 classes won't work (in case you created one object). Autowired annotation injects the object but you don't initialize object in class, so no problems appear
This is like the simplest answer.
the above answers are good i would like to tell a major difference between them .the purpose of autowiring is to avoid the dependencies between the class
if you are creating objects with new making a change to one class will effect all the classes.

How does Guice Populate Annotated Fields

For the sake of my own education, I wanted to build a simple Dependency Injection framework that functions similar to the way Google's Guice does. So that when a class is loaded, it pre-populates annotated fields with data from a factory class.
I am using Reflections to scan all my factory classes at compile time and save those classes in a static list so that when it comes time to load my classes, I have a reference to my factories that I can then scan methods and return the appropriate data.
Where i'm stuck at is how to pre-populate my classes annotated fields without actually doing any of the work in the actual class. In other words, when a class is loaded, I need to be able to determine if any of the fields are annotated with a specific annotation, and if they are, retrieve the value from the factory class.
Is there some way of performing reflection on a class right before it is loaded, pre-populate specific fields and then return an instance of that class to be used?
I could extend all of my classes that require dependency injection with a base class that does all of this work, but I figure there must be a better way so that I can simply use an #Inject (or whatever annotation I decide to use to say that this field requires DI) and "magically" all the work is done.
The way that Guice approaches this is that it will only populate the fields of an instance that was itself created by Guice1. The injector, after creating the instance, can use the Reflection API to look at the fields of the Class and inspect their annotations with Field.getDeclaredAnnotations().
This is also the reason why, when you want to inject into a static field, you need to use Binder.requestStaticInjection() to populate the static fields.
Guice does not simply scan your code for annotations; all injections recurse from an explicit request (e.g. requestStaticInjection(), Injector.getInstance(), etc). Now often that initial, explicit request will have been made in some library code.
For example, if you're using guice-servlet you let Guice create the instances of your servlet by using the serve().with() calls. But if you didn't do that, and instead left your servlet config in your web.xml, Guice would not inject into your servlet.
1 - You can also request explicit injection using Binder.requestInjection().

How to get the current bean when iterating over a JRBeanCollectionDataSource in Jasper Reports?

The Jasper Reports docs is silent on this issue and the JRDataSource interface is not explicitly allowing the access to the current bean. The current bean handle is very useful if you want to call some non property method.
The only solution I've found so far looking in the jasper reports sources is to use a _THIS field in the report and invoke the desired method on it:
${_THIS}.computeSomeValue()
Is there a better, more standard approach?
I usually use a custom_Scriptlet extending the JRDefaultScriptlet (if i ever need any other method calls pertaining to my bean). A better approach i think will be just to gather all data you will ever need (either in your bean as an instance variable with a setter/getter method or passed as a parameter when you fill your report).
This way you can leave the property bean methods take care of the rest.
Try:
$P{REPORT_DATA_SOURCE}.getData().get($V{REPORT_COUNT} - 1)

Categories

Resources