Is it possible to call static method having only class name and method name?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By AccumPlus

I want to collect classes, that are inherited from a specified class. Each derived class have static method like get_name. So I want my collection to be a dictionary with key equal to get_name-s return value and value should be a class name (or even a GDScript object, if it is possible). And I want to do this without objects instancing.

Here is a code example:

var _class_collection: Dictionary = {} 
var _class_name_list = ClassDB.get_inheriters_from_class("BaseClass")
for _class_name in _class_name_list:
    # The next function doesn`t exist, but it is the thing that I want to achieve
    var _name = ClassDB.call_static_method(_class_name, "get_name")
    _class_collection[_name] = _class_name

As far as I know, static method is like a global method, but in class namespace. So it should be possible to call method without object instancing.

Does anybody know if it is possible and how to achieve this in Godot?

:bust_in_silhouette: Reply From: AccumPlus

Ok, I didn’t know that only built-in classes exist in ClassDB. It’s a pity! I wish they would provide functionality that adds custom classes to database. It will be a useful metasystem feature.

The question is closed.

:bust_in_silhouette: Reply From: takaturre

This is a half-answer and for version 4.0. However it may come useful.

If you have the static class (eg. by loading it, using a singleton or from ClassDB if registered there with class_name (<- UPDATE: Seems this doesn’t work)) but dynamic method name, in version 4.0 you can use Callable - it works on both instantiated and static classes:

Callable(static_class, method_name).call() # You can pass in var args here.

You can also store it as well as bind arguments (returning a new callable).
However, I actually wonder if this is the preferred way to call a static class with variable method - but couldn’t find any other way (in v4.0).

Nice feature! Thank you for your answer!

AccumPlus | 2022-11-26 10:54

Notes on the earlier answer (for Godot v4.0.3):
- Unfortunately the Callable trick no longer works in Godot v4.0.3 (maybe earlier too) as the Callable constructor requires an Object (or another Callable).
- However, there’s another change as well which might be ok in some cases: If you’ve instanced an object from the static class, you can now also call its (normal or) static methods with:, ...args) or my_obj.callv(method, args)

takaturre | 2023-05-27 21:06