I need to instantiate few classes through the Java reflection api and invoke 'a' method (method invocation not through reflection) in the instantiated class. I know the reflection do impact the application performance, but I am not very sure how much it hits on the web-environment! Like the Struts framework that instantiates the Action classes using the reflection, my framework too gets the class name as string configured in the file, which I read and instantiate on different requests. How about the idea of having only one instance per class and invoke its method for every requests?
example,
package com.app.events;
public class event1 implements iEvent {
public event1() {
}
public void doprocess(Object info) {
// do necessary events
}
}
package com.app.events;
public class event2 implements iEvent {
public event1() {
}
public void doprocess(Object info) {
// do necessary events
}
}
config.xml
<events>
<event>com.app.events.Event2</event>
<event>com.app.events.Event1</event>
</events>
// servlet init
String clazName = parseXMLFile(); // not every time but only once, I have the bean
Class claz = Class.forName(clazName);
// how about this?
// I save this instance for later requests
events.put(request.getParameter("event"), claz.newInstance());
// later requests,I retrieve the event from the map and invoke its method,
// just a rough code...
events.get(request.getParameter("event")).doprocess(info);
First of all, start by respecting the Java naming conventions. Classes are CamelCased and methods are camelCased.
Using a single instance is perfectly fine. That's what servlets do, as well as Struts1 actions, and Spring beans (by default) for example. But this should be documented, because it forces every implementation of your interface to be thread-safe (preferrably, by being stateless), unless your framework makes sure only one thread uses each instance at a time, which would considerably reduce the performance of your application.
Creating many instances used to be slow, many years ago. It's not anymore now, so I would create a new instance every time, unless having a single instance is important (because initializing an instance might be slow).
Related
Nowadays we are on writing some core application that is all other application will be relying on. Without further due let me explain the logic with some codes,
We used to have a single java file that was 1000+ lines long and each application was having it as class inside, so when there was a change, each application had to edit the java file inside of it or simply fix one and copy to all. This is hard to implement as much as it is hard to maintain. Then we end-up with creating this as a separate application that is divided to smaller part, which is easy to maintain and also a core maybe a dependency to other application so we fix in one place and all other code applications are fixed too.
I've been thinking for a some great structure for this for a while want to use a builder patter for this as below
TheCore theCore = new TheCore().Builder()
.setSomething("params")
.setSomethingElse(true)
.build();
The problem arises now. Like so, I initialized the object but now I'm having access to that objects public class only. This application actually will have many small classes that has public functions that I don't want them to be static methods that can be called everytime. Instead I want those methods to be called only if TheCore class is initilized like;
// doSomething() will be from another class
theCore.doSomething()
There are some ideas I produced like
someOtherClass.doSomething(theCore)
which is injecting the main object as a parameter but still someOtherClass needs to be initialized or even a static method which doesn't make me feel comfortable and right way to that.
Actually I do not care if initializing TheCore would bring me a super object that includes all other classes inside initialized and ready to be accessed after I initialized TheCore. All I want in this structure to have a maintainable separate app and methods avaiable if only the main object which is TheCore is this circumstances is initialized.
What is to right way to achive it? I see that Java does not allow extending multiple classes even it if does, I'm not sure it that is right way...
Thanks.
After spending significant amount of time of thought I ended up that
// doSomething() will be from another class
theCore.doSomething()
is not suitable since many java classes could possibly have identical method names. So...
// doSomething() will be from another class
theCore.someOtherClass.doSomething()
would be a better approach.
To make it easier to understand I'll have to follow a complex path to explain it which is starting from the package classes first.
Think that I have a package named Tools and a class inside SomeFancyTool
main
└─java
└─com
└─<domainName>
├─Tools
| └─SomeFancyTool.java
└─TheCore.java
Now this SomeFancyTool.java must have a default access level which is actually package level access, because I don't want this classes to be accessed directly;
SomeFancyTool.java
package com.<domainName>.Tools
class SomeFancyTool{
public String someStringMethod(){
return "Some string!";
}
public int someIntMethod(){
return 123;
}
public boolean someBooleanMethod(){
return true;
}
}
So now we have the SomeFancyTool.java class but TheCore.java cannot access it since it is accesible through its Tools package only. At this point I think of an Initializer class that is gonna be in the same package, initialize these private classes and return them with a function when called. So initiliazer class would look like this;
ToolsInitializer.java
package com.<domainName>.Tools
public class ToolsInitializer{
private SomeFancyTool someFancyTool = new SomeFancyTool();
public SomeFancyTool getSomeFancyTool(){
return someFancyTool;
}
}
Since ToolsInitializer.java can initialize all functional private classes inside in Tools package and also can return them as objects to outside of the package scope, still we are not able to use these methods as we cannot import com.<domainName>.SomeFancyTool from TheCore.java because it is package wide accessible. I think here we can benefit from implementation of the java interface. A class that is not functional alone, so no problem even if it is accessed since it's methods will be nothing but declarations.
At this point I'll rename SomeFancyTool.java to SomeFancyToolImplementation.java which it will be implementing the interface and call SomeFancyTool.java to the interface itself.
SomeFancyTool.java (now as an interface)
package com.<domainName>.Tools
public interface SomeFancyTool{
public String someStringMethod();
public int someIntMethod();
public boolean someBooleanMethod();
}
and lets rename prior SomeFancyTool.java and implement the interface
SomeFancyToolImplementation.java (renamed)
package com.<domainName>.Tools
class SomeFancyToolImplementation implements SomeFancyTool{
#override
public String someStringMethod(){
return "Some string!";
}
#override
public int someIntMethod(){
return 123;
}
#override
public boolean someBooleanMethod(){
return true;
}
}
Now our structure has become like this with the final edits;
main
└─java
└─com
└─<domainName>
├─Tools
| ├─SomeFancyTool.java
| ├─SomeFancyToolImplementation.java
| └─ToolsInitializer.java
└─TheCore.java
Finally we can use our TheCore.java class to call all initializer classes with their methods to receive all these private classes inside as an object. This will allow external apps to call and initialize TheCore first to be able to access other methods.
TheCore.java
public class TheCore{
private SomeFancyToolImplementation someFancyTool;
public static class Builder{
private SomeFancyToolImplementation someFancyTool;
public Builder(){
ToolsInitializer toolsInitializer = new ToolsInitializer();
someFancyTool = toolsInitializer.getSomeFancyTool();
}
public Builder setSomeValues(){
//some values that is needed.
return this;
}
public Builder setSomeMoreValues(){
//some values that is needed.
return this;
}
public TheCore build(){
TheCore theCore = new TheCore();
theCore.someFancyTool = someFancyTool;
return theCore;
}
}
}
All Done and it is ready to use. Now the functional package classes and its methods that it relying on if TheCore is initialized or not, cannot be accessed with out TheCore. And simple usage of this Library from a 3rd Party app would simply be;
3rd Party App
TheCore theCore = new TheCore.Builder()
.setSomeValues("Some Values")
.setMoreSomeValues("Some More Values")
.build();
theCore.someFancyTool.someStringMethod();
Note: Note that a the ToolsInitializer.java is still accessible and could be used the get private method without first calling TheCore but we can always set a checker inside getSomeFancyTool() method to throw error if some prerequisites are not satisfied.
I do not still know if this is a functional structural pattern to use or its just some hard thoughts of mine. And don't know if some pattern is already exist that I just could not see yet but this is the solution I end up with.
I am implementing a Service Oriented Architecture system. There are some classes in my system that talk to an external API, so there must be some way that we can instantiate these classes when I start my program, so that they don't have to be instantiated every time someone sends a request. I was wondering if Google Guice would have something like that but so far I have found that Google Guice is good for choosing implementation class for an interface, and for by-need instantiation.
To make my question more clearer, let's say ClassAPIUser is the class which calls an external API, and it is the class I would like to instantiate in the beginning (static void main method). And let's say ClassCaller has a field of ClassAPIUser. I would like to find a way so that I can tell my program to fetch the already-instantiated ClassAPIUser from the main method (the entry-point) :
> public class ClassCaller {
>
> private ClassAPIUser classAPIUser;
>
> // Constructor
> public ClassCaller (ClassAPIUser classAPIUser) {
> this.classAPIUser = classAPIUser;
> }
> }
Is there a way I can use Google Guice to let ClassCaller know that classAPIUser is the one instantiated in the static void main method? Also, what should I be specifying in the static void main method and how should I be instantiating ClassAPIUser in the static void main method?
By default, Guice returns a new instance each time it supplies a value. This behaviour is configurable via scopes. Scopes allow you to reuse instances: for the lifetime of an application (#Singleton), a session (#SessionScoped), or a request (#RequestScoped). Guice includes a servlet extension that defines scopes for web apps. Custom scopes can be written for other types of applications.
Singleton is what you want. Take a look at the documentation.
I need to dynamically Inject a variable group of classes in my application. The purpose is, as the application grows, only have to add more classes inheriting the same interface. This is easy to do with tradicional java as I just need to search for all classes in a package and perform a loop to instantiate them. I want to do it in CDI. For example:
public MyValidatorInterface {
public boolean validate();
}
#Named
MyValidator1 implements MyValidatorInterface
...
#Named
MyValidator2 implements MyValidatorInterface
...
Now the ugly non real java code just to get the idea of what I want to do:
public MyValidatorFactory {
for (String className: classNames) {
#Inject
MyValidatorInterface<className> myValidatorInstance;
myValidatorInstance.validate();
}
}
I want to loop over all implementations found in classNames list (all will be in the same package BTW) and Inject them dynamically so if next week I add a new validator, MyValidator3, I just have to code the new class and add it to the project. The loop in MyValidatorFactory will find it, inject it and execute the validate() method on the new class too.
I have read about dynamic injection but I can't find a way to loop over a group of class names and inject them just like I used to Instantiate them the old way.
Thanks
What you are describing is what Instance<T> does.
For your sample above, you would do:
`#Inject Instance<MyValidatorInterface> allInstances`
Now, allInstances variable contains all your beans which have the given Type (MyValidatorInterface). You can further narrow down the set by calling select(..) based on qualifiers and/or class of bean. This will again return an Instance but with only a subset of previously fitting beans. Finally, you call get() which retrieves the bean instance for you.
NOTE: if you call get() straight away (without select) in the above case, you will get an exception because you have two beans of given type and CDI cannot determine which one should be used. This is implied by rules of type-safe resolution.
What you most likely want to know is that Instance<T> also implements Iterable so that's how you get to iterate over the beans. You will want to do something like this:
#Inject
Instance<MyValidatorInterface> allInstances;
public void validateAll() {
Iterator<MyValidatorInterface> iterator = allInstances.iterator();
while (iterator.hasNext()) {
iterator.next().callYourValidationMethod();
}}
}
In Java EE how can I use a variable anywhere in code without passing it down as a parameter?
Something similar to a public static variable... but a static variable is always the same for all the requests... What about a "static" variable but for the single request?
Is it possible?
Here is a little example:
I have:
protected void doGet (...)
{
Model m = Model.GetById (...);
}
public class Model
{
private String descrition;
private Market market;
private List<SparePart> spareParts;
public Model GetById ()
{
Model m = new Model ();
// get info from db using the language
this.market = Market.GetById (...);
this.spareParts = SparePart.GetByModel (m);
}
}
public class SparePart
{
private String description;
public List<SparePart> GetByModel (Model mo)
{
// get info from db using the language
}
}
public class Market
{
private String descrition;
public Market GetById (...)
{
// get info from db using the language
}
}
Both make queries to the database and retrieve informations using the language of the client... How can I set the language variable so i don't have to pass it to the methods that use it?
The anguage variable is just an example, it may happen with other variables
There are dozen ways to pass your data through execution flow in JaveEE applications. Let's assume you need to pass data within one application boundary.
Of course you can use public static final constants.
You can use public static variables, but take into account that EE
environment is extremely multithreaded. So use atomic wrappers
(AtomicInteger, etc).
You can use producers
While single request scope (http (rest) -> interseptor(s) -> bean(s)
-> response) you can use ThreadLocal
Of course you can use Stateful or Singleton beans You can use CDI
Events
If you are using Payara Server (for now the only has JCache spec
preview) you can use JCache to share your data among any
application or along the cluster as well
If you need to share your data between servers you can expose your business methods on #Remote interfaces and or share/publish/consume using JMX.
The concrete choice should depend on your App business logic.
You can set and get attributes on your ServletRequest object.
request.setAttribute("someName", someObject);
Object someObject = request.getAttribute("someName");
See the javadoc here.
Alternatively, you could use CDI (or another DI framework) and define one or more #RequestScoped objects that you can then #Inject in the places you need them.
Although not passing parameters is not a good idea in the first place, if you 'MUST' find a solution and if it matches your design, how about using inner classes? That way you declare the class variable as non-static and you can always access it from the inner classes.
In the project I'm working on (not my project, just working on it), there are many structures like this:
project.priv.logic.MyServiceImpl.java
project.priv.service.MyServiceFactoryImpl.java
project.pub.logic.MyServiceIF.java
project.pub.service.MyServiceFactoryIF.java
project.pub.service.MyServiceFactorySupplier.java
And the Service is called like this:
MyServiceFactorySupplier.getMyServiceFactory().getMyService()
I understand that a factory is used to hide the implementation of MyServiceImpl if the location or content of MyServiceImpl changes. But why is there another factory for my factory (the supplier)? I think the probability of my Factory and my FactorySupplier to change is roughly equal. Additionally I have not found one case, where the created factory is created dynamically (I think this would be the case in the Abstract Factory Pattern) but only returns MyServiceFactoryImpl.getInstance(). Is it common practice to implement a FactorySupplier? What are the benefits?
I can think of a couple of examples (some of the quite contrived) where this pattern may be useful. Generally, you have two or more implementations for your Services e.g.
one for production use / one for testing
one implementation for services accessing a database, another one for accessing a file base storage
different implementations for different locales (translations, formatting of dates and numbers etc)
one implementation for each type of database you want to access
In each of these examples, an initialization for your FactorySupplier is needed at startup of the application, e.g. the FactorySupplier is parametrized with the locale or the database type and produces the respective factories based in these parameters.
If I understand you correctly, you don't have any kind of this code in your application, and the FactorySupplier always returns the same kind of factory.
Maybe this was done to program for extensibility that was not needed yet, but IMHO this looks rather like guessing what the application might need at some time in the future than like a conscious architecture choice.
Suppose you have a hierarchy of classes implementing MyServiceIF.
Suppose you have a matching hierarchy of factory classes to create each of the instances in the original hierarchy.
In that case, MyServiceFactorySupplier could have a registry of available factories, and you might have a call to getMyServiceFactory(parameter), where the parameter determines which factory will be instantiated (and therefore an instance of which class would be created by the factory).
I don't know if that's the use case in your project, but it's a valid use case.
Here's a code sample of what I mean :
public class MyServiceImpl implements MyServiceIF
{
....
}
public class MyServiceImpl2 implements MyServiceIF
{
....
}
public class MyServiceFactoryImpl implements MyServiceFactoryIF
{
....
public MyServiceIF getMyService ()
{
return new MyServiceImpl ();
}
....
}
public class MyServiceFactoryImpl2 implements MyServiceFactoryIF
{
....
public MyServiceIF getMyService ()
{
return new MyServiceImpl2 ();
}
....
}
public class MyServiceFactorySupplier
{
....
public static MyServiceFactoryIF getMyServiceFactory()
{
return new MyServiceFactoryImpl (); // default factory
}
public static MyServiceFactoryIF getMyServiceFactory(String type)
{
Class serviceClass = _registry.get(type);
if (serviceClass != null) {
return serviceClass.newInstance ();
} else {
return getMyServiceFactory(); // default factory
}
}
....
}
I have a related hierarchy of classes that are instantiated by a hierarchy of factories. While I don't have a FactorySupplier class, I have in the base class of the factories hierarchy a static method BaseFactory.getInstance(parameter), which returns a factory instance that depends on the passed parameter.