-1

I was using the following:

String x; ... ... // x gets set somewhere in this code String y = x.replaceAll("\\s+", " ").trim();

Then I found org.apache.commons.lang3.StringUtils.normalizeSpace() which does the same thing. So at the top of my class I added

import org.apache.commons.lang3.StringUtils;

and called String y = normalizeSpace(x); but it gave me a method not found error and suggested I create the method.

So I tried import org.apache.commons.lang3.StringUtils.*;

but the same problem. Anyone have an idea what is wrong?

Yes I can, and do, use

String y = org.apache.commons.lang3.StringUtils.normalizeSpace(x);

but it gets awkward typing the entire path every time.

Oh, and I did not get a syntax error on either of the import statements. And I guess I could go back to the replace and trim but StringUtils has a lot of other methods which would be good to use also.

Tony
  • 367
  • 1
  • 7
  • 17

2 Answers2

0

You either need a static import:

import static org.apache.commons.lang3.StringUtils.*;

...

String y = normalizeSpace(x);

Or reference the class by name:

import org.apache.commons.lang3.StringUtils;

...

String y = StringUtils.normalizeSpace(x);
0

StringUtils is a class. It has a static method called normalizeSpace().

When you import the class, that simply means that you can then use the class name without the fully qualified name. So you could do this:

String y = StringUtils.normalizeSpace(x);

Since normalizeSpace() is a static method, you can also use a static import:

import static org.apache.commons.lang3.StringUtils.normalizeSpace;

And then you'd be able to use the normalizeSpace() method directly, without the class name.

However, it should be noted that static imports should be used rarely, as they make your code more difficult to follow.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107