0

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.

6
  • Please, format your code decently Commented Mar 28, 2013 at 10:31
  • 1
    If you told us what error you get (compiler warning, stack trace) we might help you. Commented Mar 28, 2013 at 10:32
  • 'They' are getting the Logger from a context make sure you do it the same way. Make sure you declare your fields correctly. Make sure you declare all the required fields. And for the love of Java show us more concrete code and the stacktrace :) Commented Mar 28, 2013 at 10:39
  • 1
    You cannot put arbitrary statements, such as an assignment statement, inside the class body, outside a method or constructor. Add a constructor to your class B and put the assignment in there. Commented Mar 28, 2013 at 10:40
  • I can't understand the relationship between A and B. Can you explain it? Commented Mar 28, 2013 at 10:40

1 Answer 1

1

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();
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Are you suggesting to write a constructor public B(Context context){log_ = (Logger) context.getAttribute(LOGGER); } But still it's not working? Or i understand it wrong... Kindly help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.