-1

I often see someone write

assertThat(Long.valueOf(1), instanceOf(Integer.class));

but am not able to figure out, why and when someone should use ClassName.class (example Integer.class) in java code

I try with https://docs.oracle.com/javase/tutorial/reflect/ resources, still hard to understand it.

J. Doem
  • 619
  • 7
  • 21
  • It means that the parameter passed is actually the class, not an instance of the class, or a variable with the same name. I don't know what he Intent object does, but it must use the class you give it in some way, probably for reflection – sForSujit Jul 29 '17 at 06:37
  • 1
    all types in java are represented by `java.lang.Class`. https://stackoverflow.com/a/19545123/5406012 – Ramanlfc Jul 29 '17 at 06:38
  • 1
    I'm not able to figure out that unit test. A Long is not an instance of an Integer – OneCricketeer Jul 29 '17 at 06:39
  • When you use Integer.class you reference an instance of Class, which is a typed class object. – sForSujit Jul 29 '17 at 06:40
  • 1
    You use it when you need it. Sorry, that is all there is to this. And the given example is not making much sense. Java is statically typed - you know all types at compile time. Thus asserting them is rather a sign of not knowing what you are doing. – GhostCat Jul 29 '17 at 06:41

2 Answers2

1

Actually calling ClassName.class is popular for example when getting a logger, In this case method expect parameter Class<?> clazz, as LoggerFactory

public static Logger More ...getLogger(Class<?> clazz) {
   Logger logger = getLogger(clazz.getName());
   ...

We can send it simply by using ClassName.class,

see answers about getLogger by class:

I usually do is

private static final Logger logger = LoggerFactory.getLogger(ClassName.class);

Or other:

I prefer

Logger logger = LoggerFactory.getLogger(ClassName.class);

Community
  • 1
  • 1
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
0

I am not overly familiar with the Hamcrest framework for matching assertions, but this would appear to be from that framework (see examp!e). The contract of the assertThat test function is that it expects parameter 1 to be a value and parameter 2 to be an instance of a class type, it will return true if paramater 1 is of parameter type 2 else false.

So ClassName.class is the actual class (through reflection I guess a reference to the name of the class), instanceOf generates an instance of that class, so instanceOf(ClassName.class) passes an instance of the class to check paramter 1 is the same type.

The overall motivation is to test the assertion that a value of Long 1 is an instance of the Integer wrapper class of the primitive int. I presume would return false in example case.

Hmm I think that makes sense.

Lew Perren
  • 1,209
  • 1
  • 10
  • 14