Link to home
Start Free TrialLog in
Avatar of Mark
Mark

asked on

How to reference "global" variable in java function.

I have a function, referenced by numerous other programs, whose parameters are not able to be changed:

static void reportDetail(Statement stmt, BufferedWriter outFile, String detailColumn) throws Exception

However, the body of the function is defined locally in any given program. What I need to do in one particular program is reference a string defined in the main program, e.g.:

String localVar = globalVar;

where globalVar is defined outside the scope of reportDetail().

Is there a way to do this? (this is jsp BTW)
Avatar of ste5an
ste5an
Flag of Germany image

You don't. Cause global variables represent state, which is a big problem when you need to test your function. Take a look at this excellent video about it.
Is it a constant?
Avatar of Mark
Mark

ASKER

CEHJ
Is it a constant?
No. In fact it is the UserAgent string obtained in the main body of the jsp program.
btw, such a value belongs to the model in MVC or the view model in MVVM.
Avatar of Mark

ASKER

ste5an: I don't know what you mean. Please explain.
Avatar of Mark

ASKER

To be specific, I need a way of getting the UserAgent string: (request.getHeader( "User-Agent" ), in a function without passing it as a function parameter.
I don't see how such a thing could work - unless you've managed to deploy your web app such that concurrent access is impossible. Otherwise, how would you know from which request the 'global' User-Agent string originated?
Avatar of Mark

ASKER

User-Agent is set on a per-request basis depending on which browser the user uses. By global, I mean global to programs in that session, not global to ALL sessions persistent over all time.

I could open a file in the main body, write the User-Agent info to it, then open that file in the function, but surely there is a better way!
If you're just talking about the session, if you can get the Request then you can get the User-Agent header
Avatar of Mark

ASKER

The problem is that the request object is not available to the function unless I add it to the parameter list as in:

static void reportDetail(Statement stmt, BufferedWriter outFile, String detailColumn, HttpServletRequest request) throws Exception

which I can't do without changing LOTS of programs, just for this one special case.
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.