0

I've got a matcher, and I want to make sue the object I have is the right type. E.g. a long or a String.

void expect(String xpath, Matcher matcher) { 
   String actual = fromXpath(xpath);
   // convert actual into correct type for matcher
   assertThat(actual, matcher);
}

I want method like Matcher.getType. So I could do something like

if (matcher.getType().equals(Long.class)) {
    long actual = Long.parseString(fromXpath(xpath));
}

But I cannot see for the life of me how I get the of the matcher.

Alex Collins
  • 980
  • 11
  • 23
  • You may want to take a look at http://stackoverflow.com/questions/3403909/get-generic-type-of-class-at-runtime I think what you are asking for is the parametric type information. In your case with the Matcher I do not know if you will be able. – Chuck Lowery Mar 19 '14 at 15:59
  • I think this is what called Type Erasure in Java, am I wrong?http://docs.oracle.com/javase/tutorial/java/generics/erasure.html – wliao Aug 02 '14 at 04:04

2 Answers2

0

Hamcrest's matcher interface does not support getting the type. The type information of Generics is erased and not available at runtime. Hence you have to create an own interface. But than you cannot use the standard matcher without wrapping them.

Stefan Birkner
  • 24,059
  • 12
  • 57
  • 72
0

If the value you're getting from fromXpath is a String, but it may be a String that can be parsed as a long, just match everything as a String.

That is, you're not missing many real problems when you change:

assertThat(a, is("abc"));
assertThat(Long.parseLong(b), is(123L));

for:

assertThat(a, is("abc"));
assertThat(b, is("123"));

So use the latter.

(Using the latter will also catch a few errors, like unexpected leading zeroes.)

Joe
  • 29,416
  • 12
  • 68
  • 88