Similar to the Object.keys method which will return a list of all the key names attached to an object, is there a way to return all static variable names and all the static method names attached to a class?
Typescript Example:
class FindStatics {
static num1:string = 'Num 1';
static num2:string = 'Num 2';
notStatic:string = "I'm not static";
static concat ():string {
return `${FindStatics.num1} loves ${FindStatics.num2}`
}
addToNonStatic(str:string):string {
return `${this.notStatic} + ${str}`;
}
}
What I would like to do is get the names of only the static variable and method names; so in the above example I would like num1
, num2
, and concat
returned.
You can invoke a static method via reflection like this : Method method = clazz. getMethod("methodname", argstype); Object o = method. invoke(null, args);
The static members of a class are accessed using the class name and dot notation, without creating an object e.g. <ClassName>. <StaticMember>. The static members can be defined by using the keyword static. Consider the following example of a class with static property.
A static method can be called directly from the class, without having to create an instance of the class. A static method can only access static variables; it cannot access instance variables. Since the static method refers to the class, the syntax to call or refer to a static method is: class name. method name.
Static methods as well as static variables are stored in the heap memory, since they are part of the reflection data (class related data, not instance related). Static variables are not stored in the heap. First its gets registration in the method area of default value and stores the values in java stack's area.
So as it turns out, you can just use the Object.keys
method to get a list of all the static variable and method names attached to a class. ES6 classes are mostly just syntactical sugar to ES5. All static properties are inherited by the class, this also works for subclassing as well, we actually get a real prototype link between a subclass constructor function and the superclass constructor.
Therefore to return all static variable and method names for the example:
Object.keys(FindStatics);
@Kirkify, Object.keys
doesn't return names of methods in my browser, because they're not enumerable.
For anyone who stumbles upon it, getOwnPropertyNames
can be the solution.
Object.getOwnPropertyNames(FindStatics) === [
"length", "prototype", "concat", "name", "num1", "num2"
]
const lengthPrototypeAndName = Object.getOwnPropertyNames(class {})
Object.getOwnPropertyNames(FindStatics).filter(
k => !lengthPrototypeAndName.includes(k)
) === ["concat", "num1", "num2"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With