How to retrieve implementing class/interface of parent interface? - java

I am clear with polymorphism and inheritance concept of oop, but I am in a situation where I need to know the implementing class. For example:
public CommonReadRepository<?> getReadRepository(String tableName) {
if (tableName == null)
return null;
switch (tableName) {
case "order":
return orderRepository;
...
}
return null;
}
The interface orderRepository extends CommonReadRepository, and because of my requirement, I need to access a function defined in orderRepository.
CommonReadRepository<?> repository=getReadRepository("order");
Is there any way to check back the implementing (child) class or interface of CommonReadRepository?
Of course, I can always do something like this:
if(tableName=="order")
return (OrderRepository)CommonReadRepository<?>;
I tried to debug getReadRepository("order"), but it gives me an instance of JdkDynamicAopProxy, and I am not sure how it works.
if(interface is instanceof xyz class)
i do not want to use it because i have 100 of classes and i want to keep it as a last resort... or in other words
i don't know about xyz class
Thanks

Following is one way to check if the returned Object is an instance of the specified class:
CommonReadRepository<?> repository=getReadRepository("order");
if(repository instanceof WhatEverSubclass) {
// do something
}
But using this approach is not how OOP is supposed to be done. If your classes all implement the same Interface, why don't you define a common method, that's then used in all the subclasses, but implement it differently every time.

I think, what you try to do is not getting you anywhere.
You can find all available classes inheriting an interface using the reflections tool (https://github.com/ronmamo/reflections). I used it for a dependency injector and it works very reliable.
Yet, why don't you just use the instanceof operator to make sure the object is of the right type:
if( repository instanceof OrderRepository) return (OrderRepository)repository;
But still, this won't change the return type of your function and you need to inspect the type of the returned value again outside of your function.
Update: If this happens for hundreds of objects, you could change the getRepository method to return a type you give as parameter: <T> getRepository(String name, Class<T> expectedType)
This will allow you OrderRepository o = getRepository("order", OrderRepository.class);

Related

Overloading in Flux mapping?

I want to stream events multiple events, all inherited from the same base type, from a mongoDB, using the spring ReactiveMongoRepository. Next I want to have them all differently handled and thus defined several overloads of a handle method, all for one child. However, the compiler complains, he can't find a proper method.
The problem is exemplarily shown in this test method:
#Test
public void polymorphismTest() {
this.createFlux()
.map(this::polymorphicMethod)
.subscribe();
}
private Flux<A> createFlux() {
A1 a1 = new A1();
a1.string1 = "foo";
A2 a2 = new A2();
a2.string2 = "bar";
return Flux.just(a1, a2);
}
private void polymorphicMethod(A1 a1) {
System.out.println(a1.string1);
}
private void polymorphicMethod(A2 a2) {
System.out.println(a2.string2);
}
I somehow understand the issue, since the compiler can't know I have a proper method for all inherited classes. However, it would be nice to have a solution similar to my approach, since it is (in my eyes) clean and readable.
I know, a solution would be to define the handle as an abstract method in the base type and implement it in the inherited classes, but this would break the functional approach of the rest of the application, plus events in a database should be POJOs.
I also would love to avoid the typical command pattern approach with one huge mapping of types to functions, but if there is no other idea this might be the solution.
You can utilize Spring to provide types to help Reactor sort appropriate "events" into appropriate "event handlers".
For example, you can define the following:
public interface EventListener<E extends EventType> {
default Class<E> getType() {
return (Class<E>) GenericTypeResolver.resolveTypeArgument(getClass(), EventListener.class);
}
Mono<Void> execute(E event);
}
You can now do this:
EventListener<E> listener = ...
sourceFlux.ofType(listener.getType()).flatMap(listener::execute)
With Spring you can define multiple EventListener instances (either by creating classes inheriting it and using #Component or defining an #Configuration with many #Bean instances of that interface) which you can collect by #Autowire or #Bean to "register" for these events.
This avoids needing to define huge maps and has about as much code as if you were trying to handle each event type anyway.

How can I add my own EnumValueMapperSupport

I'm trying to persist some enums in Hibernate and it looks like my two options for built in support are to use the name of the enum, which I would rather not do because it's string based instead of int based, or the ordinal of the enum, which I would rather not do because if I add one of the enum values at the top of the class later on, I break everything down the line.
Instead, I have an interface called Identifiable that has public int getId() as part of its contract. This way, the enums I want to persist can implement Identifable and I can know that they'll define their own id.
But when I try to extend EnumValueMapperSupport so I can utilize this functionality, I'm greeted with errors from the compiler because the EnumValueMapper interface and the EnumValueMapperSupport class are not static, and thus are expected to be locked into a given EnumType object.
How can I extend this functionality in Hibernate, short of rewriting a bunch of Hibernate code and submitting a patch. If I can't, is there another way to somehow store an enum based on something other than the ordinal or name, but instead on your own code?
In a related thought, has anyone personally been down this road and decided "let's see how bad the name mapping is" and just went with name mapping because it wasn't that much worse performance? Like, is it possible I'm prematurely optimizing here?
I'm working against Hibernate version 5.0.2-final.
At least for Hibernate 4.3.5 the EnumValueMapper is static - although private.
But you can extend EnumValueMapperSupport in an extension of EnumType:
public class ExampleEnumType extends EnumType {
public class ExampleMapper extends EnumValueMapperSupport {
...
}
}
To create an instance of this mapper you need an instance of your EnumType:
ExampleEnumType type = new ExampleEnumType();
ExampleMapper mapper = type.new ExampleMapper();
Or you create it inside your type:
public class ExampleEnumType extends EnumType {
public class ExampleMapper extends EnumValueMapperSupport {
...
}
public ExampleMapper createMapper() {
return new ExampleMapper();
}
}

implements with different data type

I have 2 class just call it "Stuff" and "Customer", the classes based on my database table (JDBC) and have abstract class because this 2 classes has same few property(Id,Name), my abstract class containing(Id,Name, along with setter and getter from Id and Name variable).
I was creating 2 more class ("ExecuteStuff" and "ExecuteCustomer") which has a goal to execute a query for manipulate a data in my database,because this situation "ExecuteStuff and ExecuteCustomer" class should have method insert, update,delete and show for manipulate and showing a data from my database, because "ExecuteStuff" and "ExecuteCustomer" need a same method for process a data from my database , I decided to creating my own interface called "myData" which is contain 4 mehod (insertData(), updateData(),deleteData() and showData()) for class "ExecuteStuff" and class "ExecuteCustomer".
My problem is, what type data should I use for parameter inside a method in my interface "myData", for example = public int insertData(Stuff stuff); this method will work for "ExecuteStuff" but not for "ExecuteCustomer" because "ExecuteStuff" and "ExecuteCustomer" has a different object type.
Or a graceful way to solve this problem.
If I understand you correctly, you can use a generic type in your interface. That way it won't matter what the data type of the parameter you pass in is.
Here is a link that explains generics:
https://docs.oracle.com/javase/tutorial/java/generics/types.html
Another solution is to use:
public int insertData(Object obj);
Since both Stuff and Customer are objects.
Hope I was able to help!
You could use a generic parameter:
interface MyData {
public <T> T insertData(T data);
}
Class example:
class MyCustomClassThat implements MyData{
#Override
public <T> T insertData(T data) {
return data;
}
}
This makes the insertData method accept any class. Then you can operate on it however you like. Finally, we return the object originally presented; just in case you operated on the data object itself.

Programmatically assess relationship between type variables in class hierarchy

Suppose I have a Java class hierarchy defined as follow:
interface Bar<T> {}
class Foo<A,B> implements Bar<B> {}
How can I programmatically assess (using reflection) that the type parameter of Bar in Foo is the second of foo's parameters and not the first (B instead of A)?
I've tried using TypeVariable#getName() in order to compare the names, but when I apply getGenericInterfaces() to Foo<A,B> I get Bar<T> and not Bar<B>
Solution (thanks to #LouisWasserman): use Foo.class.getGeenricInterfaces()[0].getActualTypeParameters() returns the correct TypeVariable (B instead of T, in the previous example)
well using TypeVariable#getName() return the type as it appears in the source code in your case it's normal to get Bar<T>. TypeVariable Doc
Using reflection in generic Classes can't help, because of Type Erasure. Erasure of Generic Types
I've the same issue in some personal projects, I tried to change the design of my class, have a look at the example below:
Instead of this:
public class Mapper<T> {
public Mapper(){
}
}
I used this:
public class Mapper {
private Class<?> entityClazz;
public Mapper(Class<?> entity){
this.entityClazz = entity
//Here I've donne all reflection issues i want !
}
}
You can use Class#isAssignableFrom() Doc to test assignability between Class Objects.
I hope this helps, good luck !

Prototyping in Java instead of extending

Is Javascript-like prototyping anyhow achievable, even using Reflection? Can I wrap my object inside another one, just to extend its functionality with one or two more methods, without wiring all its original nonprivate methods to the wrapper class, or extends is all I get?
If you are looking for extension methods, you could try Xtend. Xtend is language that compiles to java code and eliminates boilerplate code.
The following text is stolen from the Xtend Docs for extensions:
By adding the extension keyword to a field, a local variable or a parameter declaration, its instance methods become extension methods.
Imagine you want to have some layer specific functionality on a class Person. Let us say you are in a servlet-like class and want to persist a Person using some persistence mechanism. Let us assume Person implements a common interface Entity. You could have the following interface
interface EntityPersistence {
public save(Entity e);
public update(Entity e);
public delete(Entity e);
}
And if you have obtained an instance of that type (through a factory or dependency injection or what ever) like this:
class MyServlet {
extension EntityPersistence ep = Factory.get(typeof(EntityPersistence))
...
}
You are able to save, update and delete any entity like this:
val Person person = ...
person.save // calls ep.save(person)
person.name = 'Horst'
person.update // calls ep.update(person)
person.delete // calls ep.delete(person)
I don't think you can do this in Java. You can though in Groovy, using metaclasses
String.metaClass.world = {
return delegate + " world!"
}
println "Hello".world()

Categories