3

Does anybody know if I can inject an inner class in my object? I want to write something like that:

@Named
public class ClassA {

    @Inject
    private InnerClass myObject;

    public class InnerClass extends DefaultImplementation implements Serializable{
        public String overriddenMethod() {
            // do something special
        }
    }
}

I want to do these strange things because I have a default implementation which I use for injection in 80 percent of my use cases. But for special logic I have to override some methods in the default implementation.

I dont want to create an extra class file because I want to override two lines of code only.

If I try the code in my OpenWebBeans-Contrainer, I get the following Error:

javax.enterprise.inject.UnsatisfiedResolutionException: Api type [ClassA$InnerClass] is not found with the qualifiers Qualifiers: [@javax.enterprise.inject.Default()] for injection into Field: private ClassA$InnerClass ClassA.myObject

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Steven Rudolf
  • 275
  • 1
  • 8
  • 17

2 Answers2

2

Injection of inner classes should work if declared as "public static"

Layke
  • 51,422
  • 11
  • 85
  • 111
Thomas B
  • 29
  • 1
  • Thanks a lot. I realized that I can inject a static class. But I want to have a single object of a class with it's own instance variables. I think objects of a static class can only have static variables and methods. Am I wrong? – Steven Rudolf May 28 '12 at 20:53
  • **Wrong**. _No-static inner classes_ are classes which have to be created in a instance of the holder class. This means that inner class has a "holder-pointer" (can access variables of the holder). _Static inner classes_ are independent of the holder class. In both cases are classes as any other, and can have `static` and non-`static` members or methods. – lucasvc Jan 15 '15 at 08:02
1

To solve your problem simply change your class to

public static class InnerClass //...

It might seem a bit unintuitive, but java static classes are much different than a language like c#. In java static classes are used solely for the situation you are in, where you would like to utilize the nested class, without having to create an instance of the outer class first. It is actually invalid in java to create a static class without it being a nested class.

see this answer for more details: Why are you not able to declare a class as static in Java?

Community
  • 1
  • 1
Kevin DiTraglia
  • 25,746
  • 19
  • 92
  • 138