将类作为参数传递给Java中的方法 [英] Passing a class as an argument to a method in java
问题描述
如果要将类传递给方法,我正在编写一种方法,其中部分代码包括检查对象是否属于某种类型.这就是我想要的(但显然不起作用):
I am writing a method were I would like to pass a class to a method, where a part of the code includes checking if the object is of a certain type. This is what I want (but which obviously doesn't work):
private static class MyClass1 { /***/ }
private static class MyClass2 { /***/ }
private void someFunc() {
/* some code */
methodName(MyClass1);
methodName(MyClass2);
}
private void methodName(Class myClass) {
Object obj;
/* Complicated code to find obj in datastructure */
if (obj instanceof myClass) {
/* Do stuff */
}
}
关于如何完成此操作的任何提示?谢谢!
Any hints as to how this can be done? Thanks!
推荐答案
Class
都具有 isAssignableFrom()方法来检查类似的东西.最接近您要寻找的是:
Class
has both an isInstance() method and an isAssignableFrom() method for checking stuff like that. The closest to what you're looking for is:
if (myClass.isInstance(obj)) {
更新:您想在注释中将类的名称传递给方法,并检查是否有可分配给该类的东西.唯一的方法是将类名称作为String传递,然后加载该类并使用上述方法之一.例如(省略了异常处理):
Update: From your comment, you want to pass the name of a class into a method and check if something is assignable to that class. The only way to do that is to pass the class name as a String, then load the class and use one of the aforementioned methods. For instance (exception handling omitted):
private void methodName(String className) {
Class myClass = Class.forName(className);
Object obj;
/* Complicated code to find obj in datastructure */
if (myClass.isInstance(obj)) {
/* Do stuff */
}
}
这篇关于将类作为参数传递给Java中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!