我试图从另一个类的类中获取值,这些类将动态创建,也是方法。检查我经历过的这些例子。
InterfaceA.java
public interface InterfaceA{
public ArrayList<?> getValues();
}
ClassA.java / ClassB.java(考虑另一个同类有值=“世界”)
public Class A implements InterfaceA{
String value = "Hello";
public ArrayList<?> getValues(){
ArrayList<String> values = new ArrayList<String>();
values.add(this.value);
return values ;
}
}
ClassC.java
public Class C{
public void getValues(){
Object modelObject;
Method getValues;
modelObject = resolveClass("A"); // arg = classPath
getValues= modelObject.getClass().getMethod("getValues");
getValues.invoke(modelObject);
ArrayList<?> classValues;
// How to access Class A values from here
// I want to do These Lines
// classValue = get value from A/B.getValues() dynamically
}
private Object resolveClass(String className) throws
ClassNotFoundException, NoSuchMethodException, SecurityException,
InstantiationException, IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
Class<?> loadClass = Class.forName(className);
Constructor<?> constructor = loadClass.getConstructor(String.class);
Object object = constructor.newInstance(new Object[] {});
return object;
}
}
如何访问该方法返回的值为ArrayList&lt;&gt;评论中提到了什么?
答案 0 :(得分:0)
伪代码......
//copy the array of strings to a list of strings
List<String> stringList = new ArrayList<>(Arrays.asList(strArray));
// remove null
stringList.removeIf(Objects::isNull);
// do replacing
stringList.replaceAll(s -> Character.isUpperCase(s.charAt(0)) ?
s : Character.toUpperCase(s.charAt(0))+ s.substring(1));
// sort the list
tempList.sort(Comparator.naturalOrder());
您可以找到更多信息here