2013-06-19 74 views
4

我該怎麼做這個Java代碼的Dart等價物?從Dart中的字符串創建對象的實例?

Class<?> c = Class.forName("mypackage.MyClass"); 
Constructor<?> cons = c.getConstructor(String.class); 
Object object = cons.newInstance("MyAttributeValue"); 

(從傑夫·加德納)

回答

5

達特代碼:

ClassMirror c = reflectClass(MyClass); 
InstanceMirror im = c.newInstance(const Symbol(''), ['MyAttributeValue']); 
var o = im.reflectee; 

瞭解本文檔更多:http://www.dartlang.org/articles/reflection-with-mirrors/

(從吉拉德·布拉徹)

+1

'first'和'class'屬性不再在LibraryMirror上(我正在使用30188)。你如何用Dart v1做到這一點? – ringstaff

+1

謝謝,我已經更新了答案。 –

0

使用built_mirrors你可以做下一步:

library my_lib; 

import 'package:built_mirrors/built_mirrors.dart'; 

part 'my_lib.g.dart'; 

@reflectable 
class MyClass { 

    String myAttribute; 

    MyClass(this.myAttribute); 
} 

main() { 
    _initMirrors(); 

    ClassMirror cm = reflectType(MyClass); 

    var o = cm.constructors[''](['MyAttributeValue']); 

    print("o.myAttribute: ${o.myattribute}"); 
}