What is the alternative to static in java interface - java

I have a design question.
I have an interface that read XML. Each implementer class read different XML and I want a way to identify which implementer should I dynamically create for the xml type I get.
The problem is that java interface can't have static members. What is the best way to do it?
Example:
public interface MyXML{
public void readXML(String xml);
public final static String getType();
}
Usage:
func(String xml, String type)
{
MyXML obj;
switch(type)
{
case MyImpl.getType():
obj = new MyImpl();
break;
case MyImpl2.getType():
obj = new MyImpl2();
break;
}
obj.readXML(xml);
}
EDIT:
I'll try to explain better what I want:
I need to know which xml can be read by which implementation and I search for a way to force anyone that implements MyXML to tell which xml it can read so I'll not need to maintain the translation outside in another list or factory.

Java only allow static constants in the interface. In Java 8 you can have also default implementations, but that's a different thing.
One way to solve this is to make getType normal instance method, same as readXML and instantiate implementations in advance, something like this
// somewhere in the constructor or main
List<MyXML> readers = Arrays.asList(new MyImpl1(), new MyImpl2());
public MyXML findReaderForType(String type) {
for (MyXML reader : readers) {
if (reader.getType().equals(type)) {
return reader;
}
}
}
However you need to be careful to design your implementations in the way, so they can be reused.
Another option is to create some sort of static factory, which will contain the equivalent of findReaderForType method. Then the mapping between the type and implementation is contained in this factory class.

Take a look at Factory Design Pattern. The client should call the factory passing the Type, then the factory returns an instance of the correct class:
public class MyFactory {
public MyXML createMyXML(Type type) {
return ...
}
}
This way the client is free from the responsability to know which concrete class needs to be provided.

There's no point in storing implementation types in interface. The interface shouldn't know about implementations. Instead you can store the XML Type in Enum.
enum Type{
TYPE1,
TYPE2;
}
Then you can create a Map<Type, MyXML> variable and add implementations with their corresponding Type in it.
Factory can then be something like:
public MyXml getImplementation(String type){
Type type = Type.valueOf(type);
MyXml impl= implementations.get(type);
if(impl == null){
throw new UnsupportedOperationException();//or whatever ex you see fit
}
return impl;
}

I suggest you design your system around instances, not types themselves.
The application would instantiate all the XML reader types and would query each instance for the type it is in charge of. You can use that to organize the XML readers into a map and retrieve them with no switch or if-statements.
If there are some heavyweight resources associated with an instance in your current design, then change that design such that all the resource acquisition happens later into the object's lifecycle, not at construction time.
If you need several instances of the same reader at once (for example, in a concurrent setting), then use the idea exemplified by java.util.regex.Pattern and its corresponding Matcher. A pattern is a thread-safe factory of single-threaded, disposable matchers.

Related

Why do I need a FactorySupplier?

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.

Best way to pass arguments in constructor

I have a class that create rows in table layout. The row creation depend upon data and metadata. As metadata is same for each row like show/hide visibility properties etc. so I have created metadata property as a static and initialize once using initWidget of RowWidget.
just example:
class RowWidget extends FlexTable{
public static void initWidget(Form form,
HashMap<Long, ContractorPermissionEnum> formModePermissionMap,
GridMode gridMode,
boolean isApplied,
boolean isChildExist,
boolean isChildAttachment)
{
// ...
}
}
Then I called below constructor for each record data.
public RowWidget(DataRawType dataRawType, Data data, Data parentData) {
// ...
}
As I thought this is not right approach. because as pattern when anyone see this class then understand it will create one row. I don't want to call initially initWidget. I want to pass each required parameter in constructor only like
public RowWidget(DataRawType dataRawType,
Data data,
Data parentData,
Form form,
HashMap<Long, ContractorPermissionEnum> formModePermissionMap,
GridMode gridMode,
boolean isApplied,
boolean isChildExist,
boolean isChildAttachment) {
// ...
}
But due to this, constructor have no of arguments. and I think it's also bad pattern to have 5+ parameter in constructor.
Is Anyone suggest me:
How to construct class which have same property required in another
instance?
Note:I know this is possible through static only but don't want to use static.
What is best way to construct class with having some default fix
property for all instances?
Note: I don't want to create another class to achieve it. or any getter/setter method.
Thanks In advance.
I would suggest builder pattern. You would need one extra class to create RowWidget objects. So the call would look like that:
RowWidget widget = new RowWidget.Builder().withData(data).withParentData(parentData).withDataRawType(dataRawType).build();
Here is neat explanation of the pattern:https://stackoverflow.com/a/1953567/991164
Why not create method which will accept the newValues for the properties you want to change & return a new instance of the classes with all other properties copied from the instance on which you invoked this method.
You could separate/extract the parameters from the RowWidget-class fro example in a RowWidgetConfig-class.
class RowWidgetConfig {
// put here all your parameters that you need to initialize only once
// init using setters
}
Now create once instance of that class and pass it among the other parameters to RowWidget constructor.
Another alternative would be to have factory for creating RowWidget instances. The factory would also contain all the parameters you need for a row instance plus a factory method createNewRowWidget witch creates an instance base on the parameters contained in the factory.
class RowWidgetFactory {
// put here all your parameters that you need to initialize only once
// init using setters
public RowWidget createNewRowWidget() {
// create
return ...
}
}
How to construct class which have same property required in another instance?
To achive this you can have a super class with all the properties you want. So any class extending this super class will be have these properties. This way you don't need to use static keyword.
What is best way to construct class with having some default fix property for all instances?
For this one you can have an interface with some constant properties. This way any class implementing this interface will be having the fixed properties.
The static initWidget() thing just doesn't seem right for me. Though probably now you will only have one set of RowWidgets which share some properties, it is also reasonable to have 2 sets of RowWidgets, each set will have its own "shared" properties. Things will be much more fluent and you have much more choices in building more reasonable APIs if you refactor your code to make a more reasonable design
Assume now I introduce something like a RowGroup (which kind of represents the "shared" thing you mentioned)
(Honestly I don't quite get the meaning for your design, I am just making it up base on your code);
public class RowGroup {
public RowGroup(Form form,
HashMap<Long, ContractorPermissionEnum> formModePermissionMap,
GridMode gridMode,
boolean isApplied,
boolean isChildExist,
boolean isChildAttachment) { .... }
public void addRow(DataRawType dataRawType, Data data, Data parentData) {...}
}
When people use, it looks something like:
RowGroup rowGroup = new RowGroup(form, permissionMap, gridMode, isApplied, isChildExist, isChildAttach);
rowGroup.addRow(DataRawType.A, dataA, parentA);
rowGroup.addRow(DataRawType.B, dataB, parentB);
You may even provide builder-like syntax or a lot other choices.
RowGroup rowGroup
= new RowGroup(.....)
.addRow(DataRawType.A, dataA, parentA)
.addRow(DataRawType.B, dataB, parentB);
Even more important, the design now make more sense to me.
If you did not want to create another class, I'd suggest what A4L suggested.
Without creating another class, I would create constructor that takes all parameters and factory method that uses current instance as template and pass its own parameters to constructor parameter.
example (with obvious parts ommited)
class A{
public A(int p1, int p2){...}
public A create(int p2) {
return new A(this.p1,p2);
}

Java Inheritance and Wrapping

I have a generated object that I want to:
Preserve existing functionality of without injecting into the constructor and rewriting every method to call injectedObject.sameMethod().
Add additional functionality to that generated object without modifying the generated object.
add additional functionality to.
For example:
public class GeneratedObject {
public String getThis() { ... }
public String getThat() { ... }
}
public interface ObjectWrapper {
String doThisWithThat();
}
public class ObjectWrapperImpl extends GeneratedObject implements ObjectWrapper {
String doThisWithThat() { ... }
}
However, downcasting is not allowed, what is the proper implementation without rewriting a bunch of redundant code just to wrap the object?
I think decorator pattern may help you: "The decorator pattern can be used to extend (decorate) the functionality of a certain object at run-time, independently of other instances of the same class"
Have you tried aspectj? http://www.eclipse.org/aspectj/doc/next/progguide/semantics-declare.html It's a bit complicated but so is your request.
If you can extract an interface from GeneratedObject, then it would be possible to do this using a dynamic proxy. You would make a proxy which implemented the extracted interface and ObjectWrapper, with an invocation handler which passed all calls to methods in the GeneratedObject interface through to the delegate, and sent the doThisWithThat() calls elsewhere.
Proxies aren't pretty, but the ugliness is at least well-localised.

Canonicalizing Java bean property names

I have a bunch of third-party Java classes that use different property names for what are essentially the same property:
public class Foo {
public String getReferenceID();
public void setReferenceID(String id);
public String getFilename();
public void setFilename(String fileName);
}
public class Bar {
public String getRefID();
public void setRefID(String id);
public String getFileName();
public void setFileName(String fileName);
}
I'd like to be able to address these in a canonicalized form, so that I can treat them polymorphically, and so that I can do stuff with Apache BeanUtils like:
PropertyUtils.copyProperties(object1,object2);
Clearly it would be trivial to write an Adapter for each class ...
public class CanonicalizedBar implements CanonicalizedBazBean {
public String getReferenceID() {
return this.delegate.getRefID();
}
// etc.
}
But I wonder is there something out there more generalized and dynamic? Something that would take a one-to-many map of property name equivalences, and a delegate class, and produce the Adapter?
I've never used it, but I think you're looking for Dozer:
Dozer is a Java Bean to Java Bean mapper that recursively copies data
from one object to another. Typically, these Java Beans will be of
different complex types.
Dozer supports simple property mapping, complex type mapping,
bi-directional mapping, implicit-explicit mapping, as well as
recursive mapping. This includes mapping collection attributes that
also need mapping at the element level.
Dozer not only supports mapping between attribute names, but also
automatically converting between types. Most conversion scenarios are
supported out of the box, but Dozer also allows you to specify custom
conversions via XML.
First Option is Dozer.
Second option is Smooks Framework
with a tweak. It will be beneficial to use Smook's Graphical mapper.
Another option would be XStream with custom Mapper.
maybe something like that:
public class CanonicalizedBar implements CanonicalizedBazBean {
public String getReferenceID() {
Method m = this.delegate.getClass().getDeclaredMethod("getReferenceID");
if(m == null)
m = this.delegate.getClass().getDeclaredMethod("getRefID");
...
return m.invoke();
}
// etc.
}
Although, I personally have never used it. I noticed that a project called orika is noted as having the best performance and the ability to automatically understand many such mappings.
At any rate it also supports custom mappings and uses generated code to implicitly define the adapters.
You can also define a custom mapper, that is if you know how to canonize the member names you can use that knowledge to build a mapping that is true for all your objects. for instance:
DefaultFieldMapper myDefaultMapper = new DefaultFieldMapper() {
public String suggestMapping(String propertyName, Type<?> fromPropertyType) {
// split word according to camel case (apache commons lang)
String[] words= StringUtils.splitByCharacterTypeCamelCase(propertyName);
if(words[0].length() > 6) {
// trim first camel-cased word of propery name to 3 letters
words[0]= words[0].substring(0,2);
return StringUtils.join(words);
} else {
// remains unchanged
return propertyName;
}
}
}
mapperFactory.registerDefaultFieldMapper(myDefaultMapper );
I haven't done much with it but you may be able to use Aspect Oriented Programming to do this.
What you should be able to do I think is add a method to each of the classes that internally calls the real method. See this article about half way down it talks about mixins.
AspectJ is probably the most popular implementation.

how to read object attribute dynamically in java?

Is there any way to read and print the object attribute dynamically(Java) ? for example if I have following object
public class A{
int age ;
String name;
float income;
}
public class B{
int age;
String name;
}
public class mainA{
A obj1 = new A();
method(A);
method(B);
}
the output should be like
While running method(A):
Attribute of Object are age,name,income;
While executing method(B):
Attribute of Objects are age,name;
My question is I can pass various object in method(), is there any way I can access the attribute of the differnt object in general.
You want to use The Reflection API. Specifically, take a look at discovering class members.
You could do something like the following:
public void showFields(Object o) {
Class<?> clazz = o.getClass();
for(Field field : clazz.getDeclaredFields()) {
//you can also use .toGenericString() instead of .getName(). This will
//give you the type information as well.
System.out.println(field.getName());
}
}
I just wanted to add a cautionary note that you normally don't need to do anything like this and for most things you probably shouldn't. Reflection can make the code hard to maintain and read. Of course there are specific cases when you would want to use Reflection, but those relatively rare.
Using org.apache.commons.beanutils.PropertyUtils we can do this. If the proper getters and setters are defined for the bean we can also dynamically set the value:
import org.apache.commons.beanutils.PropertyUtils;
import java.beans.PropertyDescriptor;
public class PropertyDescriptorTest {
public static void main(String[] args) {
// Declaring and setting values on the object
AnyObject anObject = new AnyObject();
anObject.setIntProperty(1);
anObject.setLongProperty(234L);
anObject.setStrProperty("string value");
// Getting the PropertyDescriptors for the object
PropertyDescriptor[] objDescriptors = PropertyUtils.getPropertyDescriptors(anObject);
// Iterating through each of the PropertyDescriptors
for (PropertyDescriptor objDescriptor : objDescriptors) {
try {
String propertyName = objDescriptor.getName();
Object propType = PropertyUtils.getPropertyType(anObject, propertyName);
Object propValue = PropertyUtils.getProperty(anObject, propertyName);
// Printing the details
System.out.println("Property="+propertyName+", Type="+propType+", Value="+propValue);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
To set the value of a particular property:
// Here we have to make sure the value is
// of the same type as propertyName
PropertyUtils.setProperty(anObject, propertyName, value);
Output will be:
Property=class, Type=class java.lang.Class, Value=class genericTester.AnyObject
Property=intProperty, Type=int, Value=1
Property=longProperty, Type=class java.lang.Long, Value=234
Property=strProperty, Type=class java.lang.String, Value=string value
You can use reflection to get every field from your object (if security configuration allows you).
If you need it not for the sake of self-education, then it may be worth using ReflectionUtils from Apache Commons.
You can use reflection, but the API is not very nice to use. But what you are trying to do is not at all object-oriented. The A and B should have method "print yourself" which would output their values (you should specify the method in superclass/interface to call the method using polymorphism).
I think I would consider a different approach.
If you really want to treat these like data is there any reason they couldn't be hashtables (Do they have associated code)?
Reflection will do it but it's a last resort--you should always seriously consider different approaches before dropping to reflection.
Cases where you must access variables like that exist--like database mapping (Hibernate) and injection (Spring). You might want to consider if a packaged solution like that fits your need so that future programmers can understand what you did without learning everything about your specific solution.
Also, Spring injection can do things that might fit your needs.
Also also if you are going to use reflection, seriously consider annotations so that you aren't tying your functionality to what should be simple arbitrary attribute names.

Categories

Resources