Class type as field in Java

My question may sound strange and I don't know if this is possible, but here it is:

I have several classes (UseCases) that implement interface => IUseCase

.

UseCase1 implementing IUseCase
UseCase2 implementing IUseCase
etc.

      

I also have another class " UseCaseContext

" which should contain some information about several cases.

My goal would be to have one copy UseCaseContext

per UseCase

. For this I need a field in UseCaseContext which tells me if this context is related to UseCase1 or UseCase2 etc.

So, instead of storing an instance of UseCase in a field, is there another way to determine which UseCase

mine UseCaseContext

is related to?

I know this can be confusing, so please tell me if you need me to explain it differently :)

Thank!

+3


source to share


3 answers


Try the following:

 public class UseCaseContext {

     private Class useCaseClass;

     public UseCaseContext(Class useCaseClass) {
        this.useCaseClass = useCaseClass;
     }
 }

      



Then you can simply call: new UseCaseContext(instance.getClass())

.

+2


source


As pointed out in the comments, just store the class reference in UseCaseContext

:



public class UseCaseContext 
{
  private Class<? extends IUseCase> useCaseClass;
  ...
}

      

+5


source


IUseCase some_instance = new UseCaseX();
String className = some_instance.getClass().getSimpleName()

      

This will return UseCaseX as a string. Is this what you want?

PS If you don't need a class string name, you can use a class object (class clazz = some_instance.getClass ()) to differentiate one UseCase from another.

+3


source







All Articles