`

Create array with Array.newInstance

    博客分类:
  • java
 
阅读更多
转自http://www.java2s.com/Tutorial/Java/0125__Reflection/CreatearraywithArraynewInstance.htm

import static java.lang.System.out;

import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ArrayCreator {
  private static String s = "int bi[] = { 123, 234, 345 }";
  private static Pattern p = Pattern
      .compile("^\\s*(\\S+)\\s*\\w+\\[\\].*\\{\\s*([^}]+)\\s*\\}");

  public static void main(String... args) {
    Matcher m = p.matcher(s);

    if (m.find()) {
      String cName = m.group(1);
      String[] cVals = m.group(2).split("[\\s,]+");
      int n = cVals.length;

      try {
        Class<?> c = Class.forName(cName);
        Object o = Array.newInstance(c, n);
        for (int i = 0; i < n; i++) {
          String v = cVals[i];
          Constructor ctor = c.getConstructor(String.class);
          Object val = ctor.newInstance(v);
          Array.set(o, i, val);
        }

        Object[] oo = (Object[]) o;
        out.format("%s[] = %s%n", cName, Arrays.toString(oo));

        // production code should handle these exceptions more gracefully
      } catch (ClassNotFoundException x) {
        x.printStackTrace();
      } catch (NoSuchMethodException x) {
        x.printStackTrace();
      } catch (IllegalAccessException x) {
        x.printStackTrace();
      } catch (InstantiationException x) {
        x.printStackTrace();
      } catch (InvocationTargetException x) {
        x.printStackTrace();
      }
    }
  }
}
分享到:
评论

相关推荐

    ZendFramework中文文档

    9.5.3. Create dates from an array 9.6. Constants for General Date Functions 9.6.1. Using Constants 9.6.2. List of All Constants 9.6.3. Self-Defined OUTPUT Formats with ISO 9.6.4. Self-defined ...

    spring-framework-reference4.1.4

    Instantiation using an instance factory method ........................................... 30 4.4. Dependencies ...........................................................................................

    java泛型数组

    一个常用的替代方法是使用 `java.lang.reflect.Array` 类中的 `newInstance` 方法来创建泛型数组。这种方法能够绕过编译时的限制,实现泛型数组的创建。 ```java public class ArrayMaker&lt;T&gt; { private Class&lt;T&gt; ...

    spring-framework-reference-4.1.2

    Instantiation using an instance factory method ........................................... 30 4.4. Dependencies ...........................................................................................

    C#中数组初始化、反转和排序用法实例

    本文实例讲述了C#中数组初始化、反转和排序用法。... // Create and initialize a new array instance. Array strArr = Array.CreateInstance(typeof(string), 3); strArr.SetValue(Mahesh, 0); strA

    python3.6.5参考手册 chm

    Provisional Policy with New Header API Other API Changes ftplib functools gc hmac http html imaplib inspect io itertools logging math mmap multiprocessing nntplib os pdb pickle ...

    Java邮件开发Fundamentals of the JavaMail API

    You use the package to create Mail User Agent (MUA) type programs, similar to Eudora, pine, and Microsoft Outlook. The API's main purpose is not for transporting, delivering, and forwarding ...

    just_inform:Reginfo.gov XML 表单报告数据解析器

    基本用法 # Install the gemgem install just_inform# Load IRBirb# Create a new parser instance (same as JustInform::Parser.new)parser = JustInform.new# Return an array with the sort value (cost) and ...

    Effective java 3 学习记录.docx

    * create 或 newInstance 方法:与 instance 或 getInstance 类似,除了该方法保证每个调用返回一个新的实例,例如:Object newArray = Array.newInstance(classObject, arrayLen); * getType 方法:与 getInstance ...

    Laravel-Mapserver:Laravel 的地图服务器包

    .'Taviroquai\Mapserver\MapserverServiceProvider' ,), php composer.phar update用法// Create a MapServer instance$ mapserver = new \ Taviroquai \ Mapserver \ Mapserver ();// Create a new map object ...

    FlexGraphics_V_1.79_D4-XE10.2_Downloadly.ir

    - ADD: In the module FlexUtils added the constant BooleanWords - an array containing the words 'false' and 'true' for saving/reading TBoolProp. - ADD: In the module FlexUtils added the function ...

    Android代码-AndroidPermissionX

    create a PermissionCompat.Builder instance PermissionCompat.Builder builder = new PermissionCompat.Builder(Context); add Permissions Array builder.addPermissions(new String[]{Manifest.permission....

    JSP Simple Examples

    To use the class inside the jsp page we need to create an object of the class by using the new operator. At last use the instance of the class to access the methods of the java file. Setting Colors ...

    Sortable前端框架

    // element's new index within new parent }, // Element is dropped into the list from another list onAdd: function (/**Event*/evt) { // same properties as onEnd }, // Changed sorting within ...

    前端大厂最新面试题-2019快看漫画前端社招面经.docx

    instance.newMethod(); // 调用子类方法 ``` 【实现防抖和节流】 防抖(Debounce)和节流(Throttle)用于优化频繁触发的函数,例如窗口的resize事件或滚动事件。 - **防抖**:在一定时间内,如果函数被连续调用...

    经典小巧的表格组件 EhLib4.14

     For instance write GridsEh.TGridDrawState or Grids.TGridDrawState instead  of TGridDrawState. + In TDBGridEh  Added ContraColCount property. Property defines amount write nonscrolled  columns...

    EhLib-delphi

     For instance write GridsEh.TGridDrawState or Grids.TGridDrawState instead  of TGridDrawState. + In TDBGridEh  Added ContraColCount property. Property defines amount write nonscrolled  columns...

    Ruby连接使用windows下sql server数据库代码实例

    # Create an instance of an ADO Recordset recordset = WIN32OLE.new('ADODB.Recordset') # Open the recordset, using an SQL statement and the # existing ADO connection recordset.Open(sql, @...

    servlet2.4doc

    Adds a response header with the given name and date-value. addHeader(String, String) - Method in class javax.servlet.http.HttpServletResponseWrapper The default behavior of this method is to return ...

Global site tag (gtag.js) - Google Analytics