I
I
Ivan2014-03-26 02:31:18
Java
Ivan, 2014-03-26 02:31:18

How to implement dynamic casting of method return type in Java?

I will give an example of the task to clearly indicate the essence of the issue. I'm new to Java, so please don't kick too much, but I'm out of energy and Google doesn't help :)
So. Imagine that there are multiple implementations of the ICompany interface : CompanyImplA, CompanyImplB, and so on.
I need to write a method that would return an object of one of these classes (CompanyImplA, CompanyImplB, etc.), but at the same time this method should not initially know exactly what type of object will come inside it.
I will try to show what is required in the code

// Тип возвращаемого объекта должен каким-то образом определяться в заголовке метода (но как?)
public ТутОднаИзРеализацийICompany getCompany() {
   ICopmany company = CompanyContainer.getCurrentCompany(); // возвращает ICompany

   // далее каким-то образом кастим company из ICompany в ОднаИзРеализацийICompany, возможно получив исходный класс посредством company.getClass()

   return company; // и возвращаем уже объект приведенного типа 
}

I feel that the question is simpler than a steamed turnip and the answer lies on the surface. Please correct me if I'm completely wrong about something.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Ruslan Lopatin, 2014-03-26
@ivanm

Don't do it. That's what an interface is for, not to deal with implementation details. Use ICompany and that's it. If something is missing in the ICompany interface, then add it. Treat Impl as inner classes, inaccessible to client code.
If you really need different implementations in client code, then you don't need the ICompany interface.

M
mrstrictly, 2014-03-26
@mrstrictly

I don't fully understand the context of your problem, but it's clear that you could do well to delve into parameterized types. :)
I suspect you want this:

<T> T getCompany() {
    return (T) CompanyContainer.getCurrentCompany();
}

Note, however, that explicit type conversions are often a sign of bad design.

I
Ivan, 2014-03-26
@ivanm

The context of the task is the creation of a modular application, in which, depending on the value of an external parameter, implementations of one of the Interfaces (the implementations of which are modules) are switched. I work with Spring Framework, in particular with Spring MVC. And the implementations of the ICompany class are spring beans.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question