Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a static method on a generic type parameter in Java

Tags:

java

I would like to have something like this in Java :

import java.util.List;

class Query<T> {
    public List<T> fetch() {
        // Get the table name, T.tableName()
        // Fetch from /api/<table_name>
        // Parse and return data, T.parseJSON(jsonData)
    }
}

The intention here is to have a generic query builder, while each class T defines its specific tableName and parseJSON functions. For example,

class Article {
    public static String tableName() {
        return "article";
    }

    public static List<Article> parseJSON(String jsonData) {
        // Parse the json, build the articles
    }
}

How do I write the fetch function in the Query class?

like image 689
svr Avatar asked Nov 01 '25 23:11

svr


1 Answers

Simply pass an instance of type T so you have access to the methods of that type. Notice the comments..

public List<T> fetch(T instance) {
    // Get the table name, instance.TableName();

    // Fetch from /api/<table_name>
    // Parse and return data, instance.parseJSON(jsonData)
}
like image 185
T McKeown Avatar answered Nov 03 '25 12:11

T McKeown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!