[英]In Java, how can I determine if a char array contains a particular character?
[英]How to determine if a field is of type char[] (char array) in Java?
我通過反射動態地實例化對象,方法是將字段名稱與Map中的同名鍵進行匹配。 其中一個字段是字符數組(char []):
private char[] traceResponseStatus;
在plinko迭代器中,我有目標類的類型代碼,例如。
Collection<Field> fields = EventUtil.getAllFields(MyClass.getClass()).values();
for (Field field : fields)
{
Object value = aMap.get(field.getName());
...
else if (Date.class.equals(fieldClass))
{
例如, fieldClass
將是Date
class MyClass
{
private Date foo;
如果fieldClass類型是char [],那么測試表達式是什么?
您需要使用的代碼是:
(variableName instanceof char[])
instanceof
是一個運算符,它返回一個布爾值,指示左邊的對象是否是右邊類型的實例,即對於除null之外的所有內容,應該為variable instanceof Object
返回true,在您的情況下,它將確定您的字段是否為char數組。
你在找
else if (traceResponseStatus instanceof char[])
@ bdean20處於正確的軌道上,但是具體的(現在很明顯的)解決方案是:
if(char[].class.equals(field.getType()))
測試代碼:
import java.lang.reflect.Field;
public class Foo {
char[] myChar;
public static void main(String[] args) {
for (Field field : Foo.class.getDeclaredFields()) {
System.out.format("Name: %s%n", field.getName());
System.out.format("\tType: %s%n", field.getType());
System.out.format("\tGenericType: %s%n", field.getGenericType());
if(char[].class.equals(field.getClass()))
{
System.out.println("Class match");
}
if(char[].class.equals(field.getType()))
{
System.out.println("Type match");
}
}
}
}
輸出:
Name: myChar Type: class [C GenericType: class [C Type match
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.