1

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.

Ravenous
  • 356
  • 1
  • 4
  • 16
  • Just pass around a variable to methods that need it. – Sotirios Delimanolis Sep 30 '13 at 15:04
  • possible duplicate of [How to create new variable in java dynamically](http://stackoverflow.com/questions/5537363/how-to-create-new-variable-in-java-dynamically) – Andrea Ligios Sep 30 '13 at 15:06
  • possible duplicate of [Does Java support static variables inside a function to keep values between invocations?](http://stackoverflow.com/questions/19062467/does-java-support-static-variables-inside-a-function-to-keep-values-between-invo) – Stephen C Sep 30 '13 at 16:15

3 Answers3

4

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.

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
1

"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;
    }
}
  • 1
    `private` seems somewhat pointless and `static` might be required (`"create a static counter"`). – Bernhard Barker Sep 30 '13 at 15:21
  • Agree. I printed 'private' just habitually. But it is not so pointless as it seems. There is a namespace inside the method so private modifier can be used to hide the variable from another method local classes. Method local inner classes cant be static so they cant have static fields. –  Sep 30 '13 at 15:33
  • "to hide the variable from another method local classes" - sorry, it is better to say "from other classes except the same method local classes". –  Sep 30 '13 at 15:43
  • So if they can't be static, it won't work to create a static counter with, right? I'm not sure I understood the other part. Did you mean that it if it's private, classes inheriting that method don't have access to it? – Bernhard Barker Sep 30 '13 at 16:29
  • THis doesn't answer the question. He wants a `static.` – user207421 Oct 01 '13 at 02:11
  • Im sorry for missunderstanding, but i really tried to joke. Thought it will be funny. I know that it is not place for such things. Sorry again for irrelevant answer. –  Oct 01 '13 at 14:06
0

'static ... when needed' is a contradiction in terms. The answer is 'no'.

user207421
  • 305,947
  • 44
  • 307
  • 483