Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through classes with static functions

I have Model class like this

class ModelName {
    public static void createTable(SQLiteDatabase db){
        // code to create Table in DB
    }

    public static void deleteTable(SQLiteDatabase db){
        // code to delete Table from DB
    }
}

Every class has these static functions createTable, deleteTable
I'd like to iterate through classes like this:

SQLiteDatabase db_object = ....; //init the object
Class<?>[] models = {ModelName, OtherModelName};
for(Class<?> model : models){
    model.deleteTable(db_object);
}

But defining Interface for public static void is not possible, and I have no reason to create Instances

How to achieve this?
Can't really find the right words to describe my idea

like image 881
Marek Sebera Avatar asked Apr 27 '26 08:04

Marek Sebera


1 Answers

I don't know if this is what you are looking for but I just tested it with following.

Classes:

class ModelName {
    public static void createTable(SQLiteDatabase db){
        System.out.println(Thread.currentThread().getStackTrace()[1]);
    }

    public static void deleteTable(SQLiteDatabase db){
        System.out.println(Thread.currentThread().getStackTrace()[1]);
    }
}

class OtherModelName {
    public static void createTable(SQLiteDatabase db){
        System.out.println(Thread.currentThread().getStackTrace()[1]);
    }

    public static void deleteTable(SQLiteDatabase db){
        System.out.println(Thread.currentThread().getStackTrace()[1]);
    }
}

Main code:

Class<?>[] models = {ModelName.class, OtherModelName.class};

for(Class<?> model : models){
    Method method = model.getMethod("createTable", SQLiteDatabase.class);
    method.invoke(null, new SQLiteDatabase());
    method = model.getMethod("deleteTable", SQLiteDatabase.class);
    method.invoke(null, new SQLiteDatabase());
}

Output:

demo.reflection.ModelName.createTable(IterateClassStaticMethod.java:12)
demo.reflection.ModelName.deleteTable(IterateClassStaticMethod.java:16)
demo.reflection.OtherModelName.createTable(IterateClassStaticMethod.java:22)
demo.reflection.OtherModelName.deleteTable(IterateClassStaticMethod.java:26)

Note: To me this looks like more overhead than just creating instances. Also, the code looks less readable and manageable like this.

like image 199
Bhesh Gurung Avatar answered Apr 28 '26 23:04

Bhesh Gurung



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!