Rajesh Kumar
Rajesh Kumar

Reputation: 89

Trying use the existing Logger object, but getting <identifier expected> error?

Java logging API is used in my project. They are using logger like in constructor of a class A, for example:

public A(Context context) { 
  log_ = (Logger) context.getAttribute(LOGGER);
}

I have to implement it for a class which doesnot have a constructor... I tried to make a object of that class like in:

Class B { 
  B b; 
}

and tried to use logger like:

log_ = (Logger) b.getAttribute(LOGGER);

But I keep getting the error <identifier expected> at this line? What is fault here? Thanks in advance.

Upvotes: 0

Views: 918

Answers (1)

Raffaele
Raffaele

Reputation: 20885

You can't put arbitrary statements directly in a class definition (in fact it's a definition). You can initialize your member fields

  1. In a constructor (every class has at least a constructor, if you don't explicitely code one, the compiler will add a default constructor which takes no arguments)
  2. Directly at definition time
  3. Lazily in a method like getLogger()

All three options illustrated in (valid) Java code:

class B {

  Context ctx = Context.getDefault();
  Logger log = ctx.getLogger();

  B(Context ctx) {
    log = ctx.getLogger();
  }

  Logger logger() {
    return ctx.getLogger();
  }
}

Upvotes: 1

Related Questions