how to create a new class instance object dynamically - dart

I have a class
class Account extends Stuff{
String name;
newObject(){
return new Account();
}
}
inside the Stuff class I have a method
//generates list of objects of the same type
//as given object and fills attribute
generateObjectsFromExisting(names)
{
List list = new List();
InstanceMirror instanceMirror = reflect(this);
Symbol formatSymbol = new Symbol("newObject");
for(var name in names){
//calles newObject function from this and returns a new object
var newInstanceObject = instanceMirror.invoke(formatSymbol, []);
Symbol symbol = new Symbol("name");
InstanceMirror field = newInstanceObject.setField(symbol,name);
list.add(newInstanceObject.reflectee)
}
return list;
}
so when writing
main(){
var account = new Account();
List accounts = new List();
accounts = account.generateObjectsFromExisting(['tim','tom']);
print(account.name) // returns null
print(accounts[0].name) // returns tim
print(accounts[1].name) // returns tom
}
the problems with this way are
1 'generateObjectsFromExisting()' is on the 'account' object and not on Account
2 I have to manually add the "newObject" Method to every single class I implement.
I would prefer a static Method like 'Account.generateObjectsFromExisting()'
but how to to access 'this' (since its not available in static)
so I can say "this.new()" or something equivalent to "new Account();" eg "new this();"
and therefor be able to only have one 'newObject' function inside Stuff or maybe wont need it at all.
so now my code would look like this
class Account extends Stuff{
String name;
}
in Stuff
static generateObjectsFromExisting(names)
{
List list = new List();
for(var name in names){
var object = new this();
object.name = name;
list.add(object)
}
return list;
}
in main
main(){
// returns list of Accounts filled with names
accounts = Account.generateObjectsFromExisting(['tim','tom']);
print(accounts[0].name) // returns tim
print(accounts[1].name) // returns tom
}
if you can show me a way to access the Class to do something like this.new(); or new this(); then obviously the class 'Account' needs to be accessed and not the extended 'Stuff'
if the 'this' approach is not possible, then maybe you can show me a way how to access the Class from within an already existing object
like
generateObjectsFromExisting(names)
{
List list = new List();
var class = this.class;
var newObject = class.new():
...
}
or is my current approach the only solution. .. hope not :)
thank you

There are two ways I can think of at the moment. But both of them are pretty close to your initial solution as they both use reflection..
The non-static solution:
class Stuff {
generateObjectsFromExisting(List<String> names) {
var cm = reflectClass(this.runtimeType);
return names.map((name) {
var newInstance = cm.newInstance(const Symbol(''), []).reflectee;
newInstance.name = name;
return newInstance;
}).toList();
}
}
The static solution:
class Stuff {
static generateObjectsFromExisting(type, List<String> names) {
var cm = reflectClass(type);
return names.map((name) {
var newInstance = cm.newInstance(const Symbol(''), []).reflectee;
newInstance.name = name;
return newInstance;
}).toList();
}
}
You would call the static solution like this:
var accounts = Stuff.generateObjectsFromExisting(Account, ['tim', 'tom']);
There might be another solution involving factory constructors but can't think of any right now. Also, this code would easily break when you get another subclass of Stuff that does not have a name attribute. I don't know if you really intended on putting that attribute on Account instead of Stuff.
Also answering you 'Class'-Question. There is no class in Dart, there is only the Type and to get it you can do:
Type type1 = Account;
Type type2 = account.runtimeType;
But the Type doesn't have any methods you could use to create a new instance.

Related

frida modify static param as ArrayList

public class OBDSportsModelManager {
public static ArrayList<DataArray> mDiagnosisCommand;
public boolean getData() {
mDiagnosisCommand = new ArrayList<>();
for (String dataArray : this.commandIDs) {
mDiagnosisCommand.add(new DataArray(dataArray));
}
return true;
}
}
I want to add some more item to the 'mDiagnosisCommand',
by using this code:
sports.getData.implementation = function(){
Log.v("hook-sports", "try to add obd commands!");
var ret = this.getData();
var DataArray = Java.use("com.obd2.comm.DataArray");
var items = DataArray.$new("0x00,0x00,0x00,0x00,0x00,0x42");
this.mDiagnosisCommand.add(items); // not working!!!
Log.v("hook-sports", "hook done!");
return ret;
}
but doesn't works well.
I googled frida ArrayList add items without any help.
You have two problems:
You are using this.mDiagnosisCommand but the field is a static field, therefore it belongs to the class OBDSportsModelManager and not to the class instance this.
By calling this.mDiagnosisCommand you only get the Frida object representing this field, not the field value itself. If you want the ArrayList referenced by a field you have to add .value.
Considering both problems the following lines should work (after correcting the class name):
// correct the class name in the next line
var cls = Java.use("<full.name.to>.OBDSportsModelManager");
cls.mDiagnosisCommand.value.add(items);

Invalid constructor name

bbeginner question here:
I have a class like this
class Data {
String name;
String imgUrl;
Data(this.name, this.imgUrl);
}
and I'm trying to create a list like this
var list = new List<Data>();
var data = new Data("caca", "toto");
list.add(data);
But I get an error saying invalid constructor name.
What I'm I doing wrong here?
Thanks for your help
My guess is that your code is not inside a function. Something like:
class Something {
var list = new List<Data>();
var data = new Data("caca", "toto");
list.add(data);
}
Maybe it's due to one-too-many end braces just above the code, or some other syntactic typo.
Ensure that your code is actually inside the body of a function, not just directly inside the class.
class Something {
void tutu() {
...
var list = new List<Data>();
var data = new Data("caca", "toto");
list.add(data);
... use list ...
}
}

How can i use user define fucntion to set default value for domain class variable in grails

Here Cycle is a domain class
class Cycle {
int lenght = 42
String[] monitor = new String[length]
static mapping = {
monitor defaultValue:"defaultstrval(length)"
}
def defaultstrval(int length)
{
String[] defaultval =new String[length]
for(int i=0;i<length;i++)
{
defaultval[i]=","
}
return defaultval
}
}
Is Domain class only accept sql function.I really need help with good example.
Rather than using the mapping closure to call your function you can simply call the function from your variable assignment like so
String[] monitor = defaultstravel(length)

Get private variable by reflection in dart

I would like to get private variable in an object in dart.
This variable has no getter so I want to do this with reflection.
I try many way but nothing works to me.
For exemple, when I do this:
var reflection = reflect(this);
InstanceMirror field = reflection.getField(new Symbol(fieldName));
I get an error:
No getter for fieldName.
It's normal because the variable hasn't getter.
How can I get this variable ?
EDIT with a test code:
Here is my reflect test (test variable is a reflectClass(MyClass))
reflectClass(Injector).declarations.keys.forEach((e) => test.getField(e, test.type.owner))
I get this error:
Class '_LocalInstanceMirror' has no instance method 'getField' with
matching arguments.
If I do this:
reflectClass(Injector).declarations.keys.forEach((e) => test.getField(e))
I get:
Class 'DynamicInjector' has no instance getter
'_PRIMITIVE_TYPES#0x1b5a3f8d'.
Same thing with values of declarations.
The error message you got is actually correct. The class has a getter for this field.
Dart implicitly creates getters for all and setters for all non-final/non-const fields.
It seems access to private members isn't yet supported in Dart2JS.
see https://code.google.com/p/dart/issues/detail?id=13881
Here an example how to access private fields:
(example from https://code.google.com/p/dart/issues/detail?id=16773)
import 'dart:mirrors';
class ClassWithPrivateField {
String _privateField;
}
void main() {
ClassMirror classM = reflectClass(ClassWithPrivateField);
Symbol privateFieldSymbol;
Symbol constructorSymbol;
for (DeclarationMirror declaration in classM.declarations.values) {
if (declaration is VariableMirror) {
privateFieldSymbol = declaration.simpleName;
} else if (declaration is MethodMirror && declaration.isConstructor) {
constructorSymbol = declaration.constructorName;
}
}
// it is not necessary to create the instance using reflection to be able to
// access its members with reflection
InstanceMirror instance = classM.newInstance(constructorSymbol, []);
// var s = new Symbol('_privateField'); // doesn't work for private fields
// to create a symbol for a private field you need the library
// if the class is in the main library
// var s = MirrorSystem.getSymbol('_privateField', currentMirrorSystem().isolate.rootLibrary);
// or simpler
// var s = MirrorSystem.getSymbol('_privateField', instance.type.owner);
for (var i=0; i<1000; ++i) {
instance.setField(privateFieldSymbol, 'test');
print('Iteration ${instance.getField(privateFieldSymbol)}');
}
}
using dson or serializable you can do it in next way:
library example_lib;
import 'package:dson/dson.dart';
// this should be the name of your file
part 'example.g.dart';
#serializable
class Example extends _$ExampleSerializable {
var _privateVar;
}
main() {
var example = new Example();
example['_privateVar'] = 'some value';
print('example._privateVar: ${example._privateVar}');
print('example["_privateVar"]: ${example["_privateVar']}");
}

OntModel interface has no listHierarchyRootProperties method

Jena's OntModel has a method listHierarchyRootClasses that returns an iterator over the classes in this ontology model that represent the uppermost nodes of the class hierarchy. But why does OntModel have no method of the same function for the semantic properties? There is a property hierarchy as well, so why developers make a listHierarchyRootProperties?
I have solved this by using listAllOntProperties method, but it is a workaround, and does not look good. I don't understand why is it necessary. What is the reason?
Jena is an open-source project. You are more than welcome to submit a patch with the additional functionality you would like to see in the library. Please submit patches via the Jira account.
To answer your direct question: there's no particular reason why there's no equivalent for the property hierarchy. However, property inheritance isn't as widely used as as class inheritance in OWL, and in all the years since I wrote listHierarchyRootClasses, you're the first person I can remember asking about the property hierarchy.
Here is my workaround, which produces alphabetically sorted hierarchy (tree) of semantic properties. The getPropertyTreeModel() method returns a model for an ice:tree component and the parameter domContent is not important (it is for my special needs):
protected static DefaultTreeModel getPropertyTreeModel(OntModel ontModel, Document domContent) {
System.out.println("Creating property model...");
DefaultMutableTreeNode rootTreeNode = getRoot();
DefaultTreeModel treeModel = new DefaultTreeModel(rootTreeNode);
Iterator i = getAlphabeticalIterator(ontModel.listAllOntProperties().filterDrop(new Filter() {
#Override
public boolean accept(Object o) {
return !((OntProperty) o).listSuperProperties(true).toList().isEmpty();
}
}));
while (i.hasNext()) {
joinResource(rootTreeNode, (OntProperty) i.next(), new ArrayList(), OntProperty.class, domContent);
}
return treeModel;
}
private static Iterator getAlphabeticalIterator(ExtendedIterator ei) {
List l = ei.toList();
Collections.sort(l, new Comparator<OntResource>() {
#Override
public int compare(OntResource o1, OntResource o2) {
return (o1.getLocalName().compareTo(o2.getLocalName()));
}
});
return l.iterator();
}
private static DefaultMutableTreeNode getRoot() {
DefaultMutableTreeNode rootTreeNode = new DefaultMutableTreeNode();
ClassNodeUserObject rootObject = new ClassNodeUserObject(rootTreeNode);
rootObject.setExpanded(true);
rootTreeNode.setUserObject(rootObject);
return rootTreeNode;
}
private static void joinResource(DefaultMutableTreeNode parent, OntResource res, List occurs, Class c, Document domContent) {
DefaultMutableTreeNode branchNode = new DefaultMutableTreeNode();
SemanticNodeUserObject branchObject = (c.equals(OntClass.class))
? new ClassNodeUserObject(branchNode) : new PropertyNodeUserObject(branchNode);
branchObject.setOntResource(res);
branchObject.setExpanded(false);
branchObject.setLeaf(true);
// optimalizace: v pripade prazdneho souboru bez parsovani, aktualizace barev
if (domContent != null) {
setColorToNode(branchObject, domContent);
}
branchNode.setUserObject(branchObject);
parent.add(branchNode);
// rekurze
if (res.canAs(c) && !occurs.contains(res)) {
ExtendedIterator ei = (c.equals(OntClass.class)) ? ((OntClass) res).listSubClasses(true)
: ((OntProperty) res).listSubProperties(true);
branchObject.setLeaf(!ei.hasNext());
for (Iterator i = getAlphabeticalIterator(ei); i.hasNext();) {
OntResource sub = (OntResource) i.next();
occurs.add(res);
joinResource(branchNode, sub, occurs, c, domContent);
occurs.remove(res);
}
}
}

Resources