I want to get array of field names in the User class. eg name,age.
I tried following code -
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
Field[] fields = User.class.getDeclaredFields();
ArrayList<Field> utilList = new ArrayList<Field>(Arrays.asList(fields));
System.out.println(utilList);
}
}
class User{
String name;
int age;
}
But it is printing [java.lang.String prac1.User.name, int prac1.User.age]
.
I need to print [name,age]
with square bracket Without looping through it.
Square brackets can be attached after and before, but that is not the way I need it.It should come on its own.
Is it possible somehow using overriding toString
methods?
遍历utilList
和调用Field.getName在每个项目上。
If you are using Java 8 then you can exploit the Functional features to map a list to a new list using aa map function :
List<String> mapped = utilList.stream().map(field -> field.getName()).collect(Collectors.toList());
or
String[] mapped = utilList.stream().map(field -> field.getName()).toArray();
check this for more information ,this tutorial may help you also.
ArrayList<String> utilList = new ArrayList<String>();
for (Field field: fields) {
utilList.add(field.getName());
}
But I don't see the point of using utilList…
You can use the getName
method of Field
.
Field[] fields = User.class.getDeclaredFields();
for (Field f: fields) {
System.out.println(f.getName());
}
Output
name
age
It should be something like
Class klass = User.class;
List<String> fieldNames = new ArrayList<String>();
for(Field field: klass.getDeclaredFields()) {
fieldNames.add(field.getName());
}
System.out.println(fieldNames);
A solution using Regular Expressions, for reference:
// Class
private static final Pattern FIELD_PATTERN =
Pattern.compile("(?:[\\dA-Za-z\\.]+) (?:[\\dA-Za-z\\.]+)?\\.([A-Za-z]+)");
// Method
{
// ...
Matcher matcher=FIELD_PATTERN.matcher(utilList.toString());
while(matcher.find())
System.out.println(matcher.replaceAll("$1"));
}
You get:
[name, age]
See the regex explanation and try the code demo .
Oh, and you can build a one-liner out of this:
System.out.println(User.class.getDeclaredFields().toString().replaceAll("(?:[\\dA-Za-z\\.]+) (?:[\\dA-Za-z\\.]+)?\\.([A-Za-z]+)", "$1"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.