How to reflect on a class from an imported package with a private constructor? - reflection

I am using the reflectable library to reflect on types from imported packages (like analysis_server_client or flutter). I can reflect on types that have public constructors like Notification or Request (from the analysis_server_client package). I reflect on those types by extending those types and then using the superclassQuantifyCapability capability.
However, I am not able to reflect on types that have a private constructor like Icons (from the flutter package) since I cannot extend them. Is there a way to reflect on types like Icons that have a private constructor?

I figured it out. You have to use the GlobalQuantifyCapability which lets you declare which members to generate reflection on. It works on classes with private constructors as well. Some sample code:
#GlobalQuantifyCapability(r"^.(SomeClass|SomeEnum)", reflector)
import 'package:reflectable/reflectable.dart';
import 'package:some_package/some_class.dart';
import 'package:some_package/some_enum.dart';
class Reflector extends Reflectable {
const Reflector() : super(declarationsCapability, ...);
}
const reflector = const Reflector();

Related

RealmObject And Implement Interface

When I applied Realm in my object.
It look Like that:
public class Attribute extends RealmObject implements Parcelable, BaseEntity {}
Give me this error:
error: Only getters and setters should be defined in RealmObject classes
Who can give me the resons and solution. BIG THANKS.
Please help me !
Currently RealmObjects does not support implementing Parcable, and interfaces are only supported if they are empty or contain the getters and setter methods you would otherwise generate.
For Parcable you can consider using Parceler: https://realm.io/docs/java/latest/#parceler
Otherwise we are tracking the issue here: https://github.com/realm/realm-java/issues/878
Supporting interfaces in general will be possible once we implement support for custom methods, that can be tracked here: https://github.com/realm/realm-java/issues/909

Does Swift have access modifiers?

In Objective-C instance data can be public, protected or private. For example:
#interface Foo : NSObject
{
#public
int x;
#protected:
int y;
#private:
int z;
}
-(int) apple;
-(int) pear;
-(int) banana;
#end
I haven't found any mention of access modifiers in the Swift reference. Is it possible to limit the visibility of data in Swift?
As of Swift 3.0.1, there are 4 levels of access, described below from the highest (least restrictive) to the lowest (most restrictive).
1. open and public
Enable an entity to be used outside the defining module (target). You typically use open or public access when specifying the public interface to a framework.
However, open access applies only to classes and class members, and it differs from public access as follows:
public classes and class members can only be subclassed and overridden within the defining module (target).
open classes and class members can be subclassed and overridden both within and outside the defining module (target).
// First.framework – A.swift
open class A {}
// First.framework – B.swift
public class B: A {} // ok
// Second.framework – C.swift
import First
internal class C: A {} // ok
// Second.framework – D.swift
import First
internal class D: B {} // error: B cannot be subclassed
2. internal
Enables an entity to be used within the defining module (target). You typically use internal access when defining an app’s or a framework’s internal structure.
// First.framework – A.swift
internal struct A {}
// First.framework – B.swift
A() // ok
// Second.framework – C.swift
import First
A() // error: A is unavailable
3. fileprivate
Restricts the use of an entity to its defining source file. You typically use fileprivate access to hide the implementation details of a specific piece of functionality when those details are used within an entire file.
// First.framework – A.swift
internal struct A {
fileprivate static let x: Int
}
A.x // ok
// First.framework – B.swift
A.x // error: x is not available
4. private
Restricts the use of an entity to its enclosing declaration. You typically use private access to hide the implementation details of a specific piece of functionality when those details are used only within a single declaration.
// First.framework – A.swift
internal struct A {
private static let x: Int
internal static func doSomethingWithX() {
x // ok
}
}
A.x // error: x is unavailable
Swift 4 / Swift 5
As per mentioned in the Swift Documentation - Access Control, Swift has 5 Access Controls:
open and public: can be accessed from their module's entities and any module's entities that imports the defining module.
internal: can only be accessed from their module's entities. It is the default access level.
fileprivate and private: can only be accessed in limited within a limited scope where you define them.
What is the difference between open and public?
open is the same as public in previous versions of Swift, they allow classes from other modules to use and inherit them, i.e: they can be subclassed from other modules. Also, they allow members from other modules to use and override them. The same logic goes for their modules.
public allow classes from other module to use them, but not to inherit them, i.e: they cannot be subclassed from other modules. Also, they allow members from other modules to use them, but NOT to override them. For their modules, they have the same open's logic (they allow classes to use and inherit them; They allow members to use and override them).
What is the difference between fileprivate and private?
fileprivate can be accessed from the their entire files.
private can only be accessed from their single declaration and to extensions of that declaration that are in the same file; For instance:
// Declaring "A" class that has the two types of "private" and "fileprivate":
class A {
private var aPrivate: String?
fileprivate var aFileprivate: String?
func accessMySelf() {
// this works fine
self.aPrivate = ""
self.aFileprivate = ""
}
}
// Declaring "B" for checking the abiltiy of accessing "A" class:
class B {
func accessA() {
// create an instance of "A" class
let aObject = A()
// Error! this is NOT accessable...
aObject.aPrivate = "I CANNOT set a value for it!"
// this works fine
aObject.aFileprivate = "I CAN set a value for it!"
}
}
What are the differences between Swift 3 and Swift 4 Access Control?
As mentioned in the SE-0169 proposal, the only refinement has been added to Swift 4 is that the private access control scope has been expanded to be accessible from extensions of that declaration in the same file; For instance:
struct MyStruct {
private let myMessage = "Hello World"
}
extension MyStruct {
func printMyMessage() {
print(myMessage)
// In Swift 3, you will get a compile time error:
// error: 'myMessage' is inaccessible due to 'private' protection level
// In Swift 4 it should works fine!
}
}
So, there is no need to declare myMessage as fileprivate to be accessible in the whole file.
When one talks about making a "private method" in Swift or ObjC (or ruby or java or…) those methods aren't really private. There's no actual access control around them. Any language that offers even a little introspection lets developers get to those values from outside the class if they really want to.
So what we're really talking about here is a way to define a public-facing interface that merely presents the functionality we want it to, and "hides" the rest that we consider "private".
The Swift mechanism for declaring interfaces is the protocol, and it can be used for this purpose.
protocol MyClass {
var publicProperty:Int {get set}
func publicMethod(foo:String)->String
}
class MyClassImplementation : MyClass {
var publicProperty:Int = 5
var privateProperty:Int = 8
func publicMethod(foo:String)->String{
return privateMethod(foo)
}
func privateMethod(foo:String)->String{
return "Hello \(foo)"
}
}
Remember, protocols are first-class types and can be used anyplace a type can. And, when used this way, they only expose their own interfaces, not those of the implementing type.
Thus, as long as you use MyClass instead of MyClassImplementation in your parameter types, etc. it should all just work:
func breakingAndEntering(foo:MyClass)->String{
return foo.privateMethod()
//ERROR: 'MyClass' does not have a member named 'privateMethod'
}
There are some cases of direct assignment where you have to be explicit with type instead of relying on Swift to infer it, but that hardly seems a deal breaker:
var myClass:MyClass = MyClassImplementation()
Using protocols this way is semantic, reasonably concise, and to my eyes looks a lot like the Class Extentions we've been using for this purpose in ObjC.
As far as I can tell, there are no keywords 'public', 'private' or 'protected'. This would suggest everything is public.
However Apple may be expecting people to use “protocols” (called interfaces by the rest of the world) and the factory design pattern to hide details of the implementation type.
This is often a good design pattern to use anyway; as it lets you change your implementation class hierarchy, while keeping the logical type system the same.
Using a combination of protocols, closures, and nested/inner classes, it's possible to use something along the lines of the module pattern to hide information in Swift right now. It's not super clean or nice to read but it does work.
Example:
protocol HuhThing {
var huh: Int { get set }
}
func HuhMaker() -> HuhThing {
class InnerHuh: HuhThing {
var innerVal: Int = 0
var huh: Int {
get {
return mysteriousMath(innerVal)
}
set {
innerVal = newValue / 2
}
}
func mysteriousMath(number: Int) -> Int {
return number * 3 + 2
}
}
return InnerHuh()
}
HuhMaker()
var h = HuhMaker()
h.huh // 2
h.huh = 32
h.huh // 50
h.huh = 39
h.huh // 59
innerVal and mysteriousMath are hidden here from outside use and attempting to dig your way into the object should result in an error.
I'm only part of the way through my reading of the Swift docs so if there's a flaw here please point it out, would love to know.
As of Xcode 6 beta 4, Swift has access modifiers. From the release notes:
Swift access control has three access levels:
private entities can only be accessed from within the source file where they are defined.
internal entities can be accessed anywhere within the target where they are defined.
public entities can be accessed from anywhere within the target and from any other context that imports the current target’s module.
The implicit default is internal, so within an application target you can leave access modifiers off except where you want to be more restrictive. In a framework target (e.g. if you're embedding a framework to share code between an app and an sharing or Today view extension), use public to designate API you want to expose to clients of your framework.
Swift 3.0 provides five different access controls:
open
public
internal
fileprivate
private
Open access and public access enable entities to be used within any source file from their defining module, and also in a
source file from another module that imports the defining module. You
typically use open or public access when specifying the public
interface to a framework.
Internal access enables entities to be used within any source file from their defining module, but not in any source file outside of that
module. You typically use internal access when defining an app’s or a
framework’s internal structure.
File-private access restricts the use of an entity to its own defining source file. Use file-private access to hide the
implementation details of a specific piece of functionality when those
details are used within an entire file.
Private access restricts the use of an entity to the enclosing declaration. Use private access to hide the implementation details of
a specific piece of functionality when those details are used only
within a single declaration.
Open access is the highest (least restrictive) access level and private access is the lowest (most restrictive) access level.
Default Access Levels
All entities in your code (with a few specific exceptions) have a default access level of internal if you do not specify an explicit access level yourself. As a result, in many cases you do not need to specify an explicit access level in your code.
The release note on the topic:
Classes declared as public can no longer be subclassed outside of
their defining module, and methods declared as public can no longer be
overridden outside of their defining module. To allow a class to be
externally subclassed or a method to be externally overridden, declare
them as open, which is a new access level beyond public. Imported
Objective-C classes and methods are now all imported as open rather
than public. Unit tests that import a module using an #testable import
will still be allowed to subclass public or internal classes as well
as override public or internal methods. (SE-0117)
More information & details :
The Swift Programming Language (Access Control)
In Beta 6, the documentation states that there are three different access modifiers:
Public
Internal
Private
And these three apply to Classes, Protocols, functions and properties.
public var somePublicVariable = 0
internal let someInternalConstant = 0
private func somePrivateFunction() {}
For more, check Access Control.
Now in beta 4, they've added access modifiers to Swift.
from Xcode 6 beta 4 realese notes:
Swift access control has three access levels:
private entities can only be accessed from within the source file where they are defined.
internal entities can be accessed anywhere within the target where they are defined.
public entities can be accessed from anywhere within the target and from any other context
that imports the current target’s module.
By default, most entities in a source file have internal access. This allows application developers
to largely ignore access control while allowing framework developers full control over a
framework's API.
Access control mechanisms as introduced in Xcode 6:
Swift provides three different access levels for entities within your code. These access levels are relative to the source file in which an entity is defined, and also relative to the module that source file belongs to.
Public access enables entities to be used within any source file from their defining module, and also in a source file from another module that imports the defining module. You typically use public access when specifying the public interface to a framework.
Internal access enables entities to be used within any source file from their defining module, but not in any source file outside of that module. You typically use internal access when defining an app’s or a framework’s internal structure.
Private access restricts the use of an entity to its own defining source file. Use private access to hide the implementation details of a specific piece of functionality.
Public access is the highest (least restrictive) access level and private access is the lowest (or most restrictive) access level.
Default accecss it internal, and does as such not need to be specified. Also note that the private specifier does not work on the class level, but on the source file level. This means that to get parts of a class really private you need to separate into a file of its own. This also introduces some interesting cases with regards to unit testing...
Another point to me made, which is commented upon in the link above, is that you can't 'upgrade' the access level. If you subclass something, you can restrict it more, but not the other way around.
This last bit also affects functions, tuples and surely other stuff in the way that if i.e. a function uses a private class, then it's not valid to have the function internal or public, as they might not have access to the private class. This results in a compiler warning, and you need to redeclare the function as a private function.
Swift 3 and 4 brought a lot of change also for the access levels of variables and methods. Swift 3 and 4 now has 4 different access levels, where open/public access is the highest (least restrictive) access level and private access is the lowest (most restrictive) access level:
private functions and members can only be accessed from within the scope of the entity itself (struct, class, …) and its extensions (in Swift 3 also the extensions were restricted)
fileprivate functions and members can only be accessed from within the source file where they are declared.
internal functions and members (which is the default, if you do not explicitly add an access level key word) can be accessed anywhere within the target where they are defined. Thats why the TestTarget doesn't have automatically access to all sources, they have to be marked as accessible in xCode's file inspector.
open or public functions and members can be accessed from anywhere within the target and from any other context that imports the current target’s module.
Interesting:
Instead of marking every single method or member as "private", you can cover some methods (e.g. typically helper functions) in an extension of a class / struct and mark the whole extension as "Private".
class foo { }
private extension foo {
func somePrivateHelperFunction01() { }
func somePrivateHelperFunction02() { }
func somePrivateHelperFunction03() { }
}
This can be a good idea, in order to get better maintainable code. And you can easily switch (e.g. for unit testing) to non-private by just changing one word.
Apple documentation
For Swift 1-3:
No, it's not possible. There aren't any private/protected methods and variables at all.
Everything is public.
Update
Since Swift 4, it's possible see other answers in this thread
One of the options you could use is to wrap the instance creation into a function and supply the appropriate getters and setters in a constructor:
class Counter {
let inc: () -> Int
let dec: () -> Int
init(start: Int) {
var n = start
inc = { ++n }
dec = { --n }
}
}
let c = Counter(start: 10)
c.inc() // 11
c.inc() // 12
c.dec() // 11
The language grammar does not have the keywords 'public', 'private' or 'protected'. This would suggest everything is public. Of course, there could be some alternative method of specifying access modifiers without those keywords but I couldn't find it in the language reference.
Hopefully to save some time for those who want something akin to protected methods:
As per other answers, swift now provides the 'private' modifier - which is defined file-wise rather than class-wise such as those in Java or C# for instance. This means that if you want protected methods, you can do it with swift private methods if they are in the same file
Create a base class to hold 'protected' methods (actually private)
Subclass this class to use the same methods
In other files you cannot access the base class methods, even when you subclass either
e.g. File 1:
class BaseClass {
private func protectedMethod() {
}
}
class SubClass : BaseClass {
func publicMethod() {
self.protectedMethod() //this is ok as they are in same file
}
}
File 2:
func test() {
var a = BaseClass()
a.protectedMethod() //ERROR
var b = SubClass()
b.protectedMethod() //ERROR
}
class SubClass2 : BaseClass {
func publicMethod() {
self.protectedMethod() //ERROR
}
}
till swift 2.0 there were only three access level [Public, internal, private]
but in swift 3.0 apple added two new access level which are [ Open, fileType ] so
now in swift 3.0 there are 5 access level
Here I want to clear the role of these two access level
1. Open: this is much similar to Public but the only difference is that the Public
can access the subclass and override, and Open access level can not access that this image is taken from Medium website and this describe the difference between open and public access
Now to second new access level
2. filetype is bigger version of private or less access level than internal
The fileType can access the extended part of the [class, struct, enum]
and private can not access the extended part of code it can only access the
lexical scope
this image is taken from Medium website and this describe the difference between fileType and Private access level

Flex: load parent class into module

My main application contains a ClassA. The main application then loads a module and in that module I would like would to do:
var classA:InterfaceClassA = new ClassA();
It compiles fine but I get this warning:
Warning: YourApplication is a module or application that is directly referenced. This will cause YourApplication and all of its dependencies to be linked in with module.YourModule:Module. Using an interface is the recommended practice to avoid this.
I can't use an interface to generate the new instance, so what is the correct way to do this?
I found an answer in Accessing the parent application from the modules . I created a helper class in the main Application that contains instances of the classes I want to access. In the module I then use:
parentApplication.myModuleHelper.**myClassInstance**.myMethod();
for instance methods and for static class level methods I use:
parentApplication.myModuleHelper.**MyClassInstance**.myMethod()
To get an instance of my class in a module I use this in MyModuleHelper
public function getFullScreenUtil(iFullScreenUtil:IFullScreenUtil , iSystemManager:ISystemManager):FullScreenUtil {
return new FullScreenUtil(iFullScreenUtil , iSystemManager);
}
and this in MyModule:
var _fullScreenUtil:* = parentApplication.moduleHelper.getFullScreenUtil(this , systemManager);
which is all I need for now. I am not sure how I could cast the result of getFullScreenUtil(..) to an actual instance of FullScreenUtil but I expect that it can not be done in modules. Maybe using an interface would provide the solution to that.

Flex: Variable accessible for all .mxml files

Im using Oracle, BlazeDS, Java & Flex. I have an ArrayCollection containing data from a small database table. This table won't be the subject of much change. I want to use this ArrayCollection accross different mxml files to fill e.g. ComboBoxes etc.
The reason for asking, is that doing a database call for each time a fill a ComboBox etc is slow and seems unnecessary. I tried doing this once in the "main" .mxml file, but then the variable wasn't accessible where i needed it.
What is the best approach for accomplishing this task? What is the best way of making a variable accesible across .mxml files? :)
[Bindable] public static var yourArrayCollection:ArrayCollection
That should make it visible anywhere but using static variables is normally not a good idea.
You could also implement a singleton instance to persist a variable if you do not want to make it static and need to reference other functions etc - but I think the static variable should do fine.
If this is a larger application, I'd recommend looking at Parsley: http://www.spicefactory.org/parsley/. With Parsley, you could add the array collection to the context and simply inject it whenever you need to reference it. The array collection should be populated during application startup and can be updated as needed.
There basically are two ways. The singleton way, and the static class way. A singleton is a class that is only instanciated once, through a mechanism described here, for instance. A static class is a bit different from a regular class : you will not instanciate it, first of all.
For more information about how implement a singleton in ActionScript 3 : here.
For more information about static classes and variables : here.
You can just make it public member of some class and import that class in all MXML-based classes:
public class DBWrapper {
[Bindable]
public var ItemList:ArrayCollection;
}
I usually make it a static member of a Globals class
public class Globals {
[Bindable] public var iCollection:ArrayCollection;
}
It can be accessed from anywhere in the program (provided you have assigned a valid ArrayCollection to it first)
combobox.dataProvider=Globals.iCollection;

How do you work around the need to cast an interfaced object back to its base class?

This question is meant to apply to interfaces in general, but I'll use AS3/Flex for my language. It should be [mostly] obvious how to apply it in different languages.
If I create a base class, and it extends an interface, there is an explicit contract defined: for every method in the interface, the base class must implement said method.
This is easy enough. But I don't understand why you have the capacity to cast an interfaced instance back to its original base class. Of course, I've had to do this a few times (the example below is very close to the situation I'm struggling with), but that doesn't mean I understand it :^)
Here's a sample interface:
public interface IFooable extends IUIComponent {
function runFoo():void;
}
Let's say I create a base class, which extends VBox and implements the interface:
public class Foo extends VBox implements IFooable {
public Foo() {
super();
//stuff here to create Foo..blah blah
}
public function runFoo():void {
// do something to run foo
}
}
Now, the reason I used the interface, is because I want to guarantee "runFoo" is always implemented. It is a common piece of functionality all of my classes should have, regardless of how they implement it. Thus, my parent class (an Application) will instantiate Foo via its interface:
public function init():void {
var foo:IFooable = new Foo();
foo.percentHeight = 100; //works because of IUIComponent
}
But, if I want to add Foo to the Application container, I now have to cast it back to the base class (or to a different base class):
public function init():void {
var foo:IFooable = new Foo();
foo.percentHeight = 100;
addChild(foo as DisplayObject); //_have_ to cast, because addChild takes a 'DisplayObject' class type
//could also do this:
//addChild(foo as VBox);
}
Wasn't the original intention to hide the implementation of Foo? There is still an assumption that Foo is a DisplayObject. Unfortunately, being able to add the custom object to a container seems impossible without casting.
Am I missing something entirely? Is this really just a phenomenon in Flex/AS3? If you have a container in the base API of a language, and it only allows you to add children of a certain class type, how do you then abstract out implementation?
For the record, this question appears to ask if this sort of operation is possible, but it doesn't really address why it might be bad design (and how to fix it).
2nd Thought:
Abstract Classes:
As Matthew pointed out, abstract classes helps solve some of this: I could create a base abstract class which inherits from the DisplayObject (or, in my case, the VBox, since it is a child of DisplayObject), and have the base class implement the interface. Thus, any class which extends the abstract class would then be required to implement the methods therein.
Great idea -- but AS3 doesn't have abstract classes (to my knowledge, anyway).
So, I could create a base class which implements interface and extends the VBox, and inherit from it, and I could insert code in those methods which need to be extended; such code would throw an error if the base class is the executor. Unfortunately, this is run-time checking as opposed to compile-time enforcement.
It's still a solution, though.
Context:
Some context might help:
I have an application which can have any number of sub-containers. Each of these sub-containers will have their own respective configuration options, parameters, etc. The application itself, however, has a global ApplicationControlBar which will contain the entry-point Menu for accessing these configuration options. Therefore, whenever I add a sub-component to the main Application (via "addChild"), it will also "register" its own configuration options with the ApplicationControlBar menu. This keeps the knowledge of configurability with the containers themselves, yet allows for a more unified means of accessing them.
Thus, when I create each container, I want to instantiate them via their interface so I can guarantee they can register with the ApplicationControlBar. But when I add them to the application, they need to be the base class.
#James Ward, That's definitely something I wish was in the language, probably a interface IDisplayObject. That would solve a lot of issues in OOP display programing in AS3.
In regards the the original question, something I've used in the past, and have seen mentioned on www.as3dp.com is to include a getDisplay():DisplayObject method in the interface, which would typically return "this" by its implementor. It's less than ideal, but works.
#Matthew Flaschen, While we don't have Abstarct Classes native to AS3, common practice is to name the class with the word Abstract ie: AbstarctMyObject, and then just treat it like the abstarct objects in Java and other languages. Our want for true abstarct classes is something the Flash player team is well aware of, and we'll likly see it in the next version of the ActionScript language.
Okay, I'm anaswering generally, because you said, "Is this really just a phenomenon in Flex/AS3?".
In your init method, obviously you're always calling addChild with foo. That means foo must always be an instance of DisplayObject. You also want it to be an instance of IFooable (though it's not clear here why). Since DisplayObject is a class, you would consider using a subclass of DisplayObject (e.g. FooableDisplayObject), that implemented IFooable. In Java, this would the below. I'm not familiar with AS, but I think this shows there's not any general flaw in interfaces here.
interface IFooable
{
public void runFoo();
}
class DisplayObject
{
}
abstract class FooableDisplayObject extends DisplayObject implements IFooable
{
}
class Foo extends FooableDisplayObject
{
public void runFoo()
{
}
}
public void init()
{
FooableDisplayObject foo = new Foo();
foo.percentHeight = 100;
addChild(foo);
}
I think this is a place where Flex's/Flash's API is not correct. I think that addChild should take an interface not a class. However since that is not the case you have to cast it. Another option would be to monkey patch UIComponent so that it takes an interface or maybe add another method like addIChild(IUIComponent). But that's messy. So I recommend you file a bug.
Situation here is that it should be just the other way around for optimal practice... you shouldn't look to cast your interface to a displayobject but to have your instance already as a displayobject and then cast that to your interface to apply specific methods.
Let's say I have a baseclass Page and other subclasses Homepage, Contactpage and so on. Now you don't apply stuff to the baseclass as it's kind of abstract but you desing interfaces for your subclasses.
Let's say sub-pages implement for example an interface to deal with init, addedtostage, loader and whatever, and another one that deals with logic, and have eventually the base req to be manageble as displayobjects.
Getting to design the implementation.. one should just use an interface for specialized stuff and extend the subclass from where it mainly belongs to.. now a page has a 'base' meaning to be displayed (design wise.. the 'base'-class is a displayobject) but may require some specialization for which one builds an interface to cover that.
public class Page extends Sprite{...}
public interface IPageLoader{ function loadPage():void{}; function initPage():void{}; }
public class Homepage extends Page implements IPageLoader
{ function loadPage():void{/*do stuff*/}; function initPage():void{/*do stuff*/}; }
var currentpage:Page;
var currentpageLoader:IPageLoader;
currentpage = new Homepage;
currentpageLoader = currentpage as IPageLoader;
currentpageLoader.loadPage();
currentpageLoader.initPage();
addChild(currentpage);
Tween(currentpage, x, CENTER);

Resources