1. Overview
1.概述
In this article, we’ll explore the different ways of finding an object’s class in Java.
在这篇文章中,我们将探讨在Java中寻找一个对象的类的不同方法。
2. Using the getClass() Method
2.使用getClass()方法
The first method that we’ll check is the getClass() method.
我们要检查的第一个方法是getClass()方法。
First, let’s take a look at our code. We’ll write a User class:
首先,让我们看一下我们的代码。我们将写一个User类。
public class User {
// implementation details
}
Now, let’s create a Lender class that extends User:
现在,让我们创建一个Lender类,它扩展了User。
public class Lender extends User {
// implementation details
}
Likewise, we’ll create a Borrower class that extends User as well:
同样地,我们将创建一个Borrower类,它也扩展了User。
public class Borrower extends User {
// implementation details
}
The getClass() method simply returns the runtime class of the object we are evaluating, hence, we don’t consider inheritance.
getClass()方法只是返回我们正在评估的对象的运行时类,因此,我们不考虑继承。
As we can see, getClass() shows that our lender object’s class is of type Lender but not of type User:
我们可以看到,getClass()显示我们的lender对象的类是Lender类型,而不是User类型。
@Test
public void givenLender_whenGetClass_thenEqualsLenderType() {
User lender = new Lender();
assertEquals(Lender.class, lender.getClass());
assertNotEquals(User.class, lender.getClass());
}
3. Using the isInstance() Method
3.使用isInstance()方法
When using the isInstance() method, we’re checking if an object is of a particular type, and by type, we are either talking about a class or an interface.
当使用isInstance()方法时,我们正在检查一个对象是否属于一个特定的类型,通过类型,我们谈论的是一个类或一个接口。
This method will return true if our object sent as the method’s argument passes the IS-A test for the class or interface type.
如果我们发送的作为方法参数的对象通过了该类或接口类型的IS-A测试,该方法将返回true。
We can use the isInstance() method to check the class of an object at runtime. Furthermore, isInstance() handles autoboxing as well.
我们可以使用isInstance()方法来在运行时检查对象的类别。此外,isInstance()也可以处理autoboxing。
If we check the following code, we’ll find that the code doesn’t compile:
如果我们检查下面的代码,我们会发现该代码不能编译。
@Ignore
@Test
public void givenBorrower_whenDoubleOrNotString_thenRequestLoan() {
Borrower borrower = new Borrower();
double amount = 100.0;
if(amount instanceof Double) { // Compilation error, no autoboxing
borrower.requestLoan(amount);
}
if(!(amount instanceof String)) { // Compilation error, incompatible operands
borrower.requestLoan(amount);
}
}
Let’s check the autoboxing in action using the isInstance() method:
让我们使用isInstance()方法来检查自动投币的操作。
@Test
public void givenBorrower_whenLoanAmountIsDouble_thenRequestLoan() {
Borrower borrower = new Borrower();
double amount = 100.0;
if(Double.class.isInstance(amount)) { // No compilation error
borrower.requestLoan(amount);
}
assertEquals(100, borrower.getTotalLoanAmount());
}
Now, let’s try to evaluate our object at run time:
现在,让我们试着在运行时评估我们的对象。
@Test
public void givenBorrower_whenLoanAmountIsNotString_thenRequestLoan() {
Borrower borrower = new Borrower();
Double amount = 100.0;
if(!String.class.isInstance(amount)) { // No compilation error
borrower.requestLoan(amount);
}
assertEquals(100, borrower.getTotalLoanAmount());
}
We can also use isInstance() to verify whether an object can be cast to another class before casting it:
我们还可以使用isInstance()来验证一个对象是否可以在投递前投递到另一个类。
@Test
public void givenUser_whenIsInstanceOfLender_thenDowncast() {
User user = new Lender();
Lender lender = null;
if(Lender.class.isInstance(user)) {
lender = (Lender) user;
}
assertNotNull(lender);
}
When we make use of the isInstance() method, we protect our program from attempting illegal downcasts, although, using the instanceof operator will be smoother in this case. Let’s check it next.
当我们利用isInstance()方法时,我们保护了我们的程序,避免尝试非法的降级,尽管,在这种情况下,使用instanceof操作符会更顺畅。接下来让我们检查一下。
4. Using the instanceof Operator
4.使用instanceof操作符
Similarly to the isInstance() method, the instanceof operator returns true if the object being evaluated belongs to the given type — in other words, if our object referred to on the left side of the operator passes the IS-A test for the class or interface type on the right side.
与isInstance()方法类似,instanceof操作符在被评估的对象属于给定类型时返回true–换句话说,如果我们在操作符左侧提到的对象通过了右侧的类或接口类型的IS-A测试。
We can evaluate if a Lender object is type Lender and type User:
我们可以评估一个Lender对象是否是Lender类型和User类型。
@Test
public void givenLender_whenInstanceOf_thenReturnTrue() {
User lender = new Lender();
assertTrue(lender instanceof Lender);
assertTrue(lender instanceof User);
}
To get an in-depth look at how the instanceof operator works, we can find more information in our Java instanceOf Operator article.
要深入了解instanceof操作符的工作原理,我们可以在Java instanceOf Operator文章中找到更多信息。
5. Conclusion
5.总结
In this article, we reviewed three different ways of finding an object’s class in Java: the getClass() method, the isInstance() method, and the instanceof operator.
在这篇文章中,我们回顾了在Java中寻找一个对象的类的三种不同方法:getClass()方法、isInstance()方法和instanceof操作符。
As usual, the complete code samples are available over on GitHub.
像往常一样,完整的代码样本可以在GitHub上找到over。