-2

I am trying to create a static method that returns a Generic Object of the same class which the static method is a member of but there is compilation error on the return type as

Cannot make a static reference to the non-static type T

Looking at other solutions on stack overflow I found this (Generics)Cannot make a static reference to the non-static type T

where a responder has provided an answer which says that for static methods, we must also include the target type before the return type but even this does not work

public class Condition<T extends Node> {

private boolean isInitialized=false;
private ConditionType type;
private NodeType nodeType;
private String propertyName;
private Predicate<T> onlyIfTest;
private Predicate<T> predicates;

private Condition() {

}

//Here at the return type i get the error Cannot make static...
public static Condition<T> include(NodeType type,String propertyName) {
    Condition<T> condition = new Condition<T>(); //and an error here too
    condition.type = ConditionType.INCLUDE;
    condition.nodeType = type;
    condition.propertyName = propertyName;
    condition.isInitialized =true;
    return condition;
}

The error that i get is Cannot make a static reference to the non-static type T. How can i make it work with a static method.

fdfdfd
  • 501
  • 1
  • 7
  • 21
Raghave Shukla
  • 281
  • 1
  • 3
  • 12

3 Answers3

2

Each instance of Condition has its own generic type T. There's nothing in the static method indicating what T is supposed to be. You could add <T> as a generic type parameter to the static method if that's what you want.

For example:

public static <T> Condition<T> include(NodeType type, String propertyName) {
    ...
}
khelwood
  • 55,782
  • 14
  • 81
  • 108
0

You've already had your answer:

we must also include the target type before the return type

but didn't apply it.

public static <T extends Node> Condition<T> include(NodeType type, String propertyName)
jsamol
  • 3,042
  • 2
  • 16
  • 27
  • Thanks Julia but somehow even that is not working. You can try that and let me know if the results are different. I think its got something to do with me returning the object of the same class from the static method – Raghave Shukla Aug 01 '19 at 14:32
  • @RaghaveShukla Sorry, my bad. I didn't notice the generic type extends `Node`. Check the edited answer and let me know if that solves your problem. – jsamol Aug 01 '19 at 14:36
  • Perfecto ! Thank you very much. Now i have a cleaner code :) – Raghave Shukla Aug 01 '19 at 14:38
0

I think your syntax is wrong

public class Condition<T> {
//...

    public static <T> Condition<T> include() {
    Condition<T> condition = new Condition<T>();
    return condition;
    }

}