Reputation: 356
Is it possible to declare a class level variable from within a method?
I'm simply trying to create a static counter, but I only want to create it if needed. The class calling it should live longer than the function itself.
My need for this is rare, but I'm interested if it would work.
Upvotes: 1
Views: 2645
Reputation: 310980
'static ... when needed' is a contradiction in terms. The answer is 'no'.
Upvotes: 0
Reputation:
"Is it possible to declare a class level variable from within a method?"
If literally - yes :) it is possible with method-local classes :
void method() {
class LocalClass {
private Object variable;
}
}
Upvotes: 1
Reputation: 62835
Not it is not possible to declare class level field, unless you're doing some metaprogramming stuff like insane bytecode level modification that wouldn't pay for itself. All declaration is done at compile time.
Upvotes: 4