Create object instance without invoking constructor? - c#

In C#, is there a way to instantiate an instance of a class without invoking its constructor?
Assume the class is public and is defined in a 3rd party library and the constructor is internal. The reasons I want to do this are complicated but it would be helpful to know if it's possible using some kind of C# hackery.
NOTE: I specifically do not want to call any constructor so using reflection to access the internal constructor is not an option.

I have not tried this, but there is a method called FormatterServices.GetUninitializedObject that is used during deserialization.
Remarks from MSDN says:
Because the new instance of the object
is initialized to zero and no
constructors are run, the object might
not represent a state that is regarded
as valid by that object.

Actually it sounds like they made the constructor internal just so you can't instantiate it. It may have a builder or factory method.
Check out these articles:
Preventing Third Party Derivation: Part 1
Preventing Third Party Derivation: Part 2
they kind of explain the reasoning.

Contrary to what many believe, a constructor hasn't much to do with the instantiation of an object at all (pretty misleading term). A constructor is a special method that can be called after the instantiation of an object to allow that object to properly initialize itself. In C++ object instantiation allocates memory for the object, in .NET and Java it is both allocated and pre-initialized to default values depending on the type of fields (0, null, false etc.). Then the run-time calls the constructor. The new operator encapsulates these two separate actions into what appears to be a single operation.
Deserialization could never had worked in .NET if it wasn't possible to create an instance without using a constructor. That said, the so called ConstructorInfo type acts as both a new operator and constructor when calling its Invoke(...) method.

See RuntimeHelpers.GetUninitializedObject(Type), available in .NET Core 2.0 / .NET Standard 2.1 and above.
Another answer suggests
FormatterServices.GetUninitializedObject(Type), which directly proxies to RuntimeHelpers.
For completeness, if you want to create an uninitialized object of the same type as another instance, in .NET Core 7 there is also an undocumented AllocateUninitializedClone, with sample code below. I wouldn't recommend this over simply passing instance.GetType() to the documented API.
Likewise, here are notes for if you actually want to hit an internal constructor:
Given a Type and some arguments.
Use Activator.CreateInstance(Type type, object[] args).
Alternatively via Reflection APIs
Use type.GetConstructor. The returned ConstructorInfo has an Invoke method. If you pass an instance, you will effectively reinitialize an object. If you pass no instance, the invocation will instantiate a new object.
Some sample code:
using System.Reflection;
using System.Runtime.CompilerServices;
public static class Program {
public static void Main() {
//
// create uninitialized object instance, then run ctor on it
//
var inst1 = (C)RuntimeHelpers.GetUninitializedObject(typeof(C));
Console.WriteLine(inst1.X); // 0
var ctor = typeof(C).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Array.Empty<Type>());
ctor.Invoke(inst1, null); // Prints "Ran C's Ctor. X is -123"
Console.WriteLine(inst1.X); // 2
//
// create new object with ctor (via reflection)
//
var inst2 = (C)ctor.Invoke(null); // Prints "Ran C's Ctor. X is -123"
Console.WriteLine(inst2.X); // 2
//
// create new object with ctor (via activator)
//
var inst3 = (C)Activator.CreateInstance(typeof(C), BindingFlags.Instance | BindingFlags.NonPublic, null, null, null); // Prints "Ran C's Ctor. X is -123"
Console.WriteLine(inst3.X); // 2
//
// create new uninitialized object of type matching a given instance via undocumented AllocateUninitializedClone
//
var allocateUninitializedClone = typeof(RuntimeHelpers).GetMethod("AllocateUninitializedClone", BindingFlags.Static | BindingFlags.NonPublic, new[] { typeof(object) });
var inst4 = (C)allocateUninitializedClone.Invoke(null, new []{inst2});
Console.WriteLine(inst4.X); // 0
}
public class C {
private C() {
Console.WriteLine($"Ran C's Ctor. X is {X}");
X = 2;
}
public int X { get; } = -123;
}
}

It might be possible to access the constructor via reflection and invoke it like that (but I'm not sure that it will work since the constructor is internal - you'll have to test it).
Otherwise from my knowledge you can't create an object without calling the constructor.

EDIT: You updated your question, you want to construct a class without a constructor. Or call a default "Empty Constructor".
This cannot be done, as the compiler will not generate a default constructor if there is already one specified. However, for the benefit of the readers, here is how to get at a internal, protected, or private constructor:
Assuming your class is called Foo:
using System.Reflection;
// If the constructor takes arguments, otherwise pass these as null
Type[] pTypes = new Type[1];
pTypes[0] = typeof(object);
object[] argList = new object[1];
argList[0] = constructorArgs;
ConstructorInfo c = typeof(Foo).GetConstructor
(BindingFlags.NonPublic |
BindingFlags.Instance,
null,
pTypes,
null);
Foo foo =
(Foo) c.Invoke(BindingFlags.NonPublic,
null,
argList,
Application.CurrentCulture);
Ugly, but works.
Of course, there may be a perfectly legitimate reason to mark a constructor as internal, so you should really consider the logistics of what you want before you abuse that class by getting at it with reflection.

You have to call a constructor to create an object. If there are none available to your liking perhaps you could use a byte code rewriting library like the Mono project's Cecil. It works on Windows as well as Linux. From some of the demos I saw, it looked pretty cool. You can change the protection levels of methods and all sorts of crazy stuff.

If the class (and the classes of objects that it references) is Serializable, you can create a deep copy by serializing using a BinaryFormatter that outputs to a MemoryStream (creating a byte array byte[]), then deserializing. See the answers to this question on converting an object to a byte array. (But note - saving the byte array to use later/elsewhere is likely not to work. IOW don't save the byte array to a file or other persistent form.)

See the System.Activator.CreateInstance function.

What you are asking to do is a violation of the philosophy upon which managed programming was developed. The .Net Framework and C# are built with the principle that, whenever possible, objects should be abstracted away from their underlying memory. Objects are objects, not a structured array of bytes. This is why you can't cast objects to void pointers willy-nilly. When objects are abstracted away from their underlying memory, it is fundamentally invalid to suggest that an object instance can exist without the constructor being invoked.
That said,the .Net framework has made concessions to the fact that in reality, objects are actually represented in memory. With some creativity, it is possible to instantiate value types without invoking their initializers. However, if you feel you need to do it, you're probably doing things wrong.

I noticed the "deadness" of the subject but just for clarification on further readers and to put a final answer that maybe wasn't possible when the question was posted. Here it goes.
It seems that you can instantiate a class without using it's constructors by assigning values to its properties. Here is the address where is the how-to in MSDN for this type of instantiation http://msdn.microsoft.com/en-us/library/bb397680.aspx.
It seems like this is a technique that's not well known because I encountered it in a article in CodeProject and then googled it and didn't find anything about it and later on visited the MSDN Homepage and there was a post that linked me to that exact subject. So it seems that it's an unknown subject rather than a new one because the date on the CodeProject post dates May 2008.
Hope this helps someone else that google's this and comes across with this question.

No one here has quite clarified what is meant by "It can't be done."
The constructor is what creates the object. Your question is akin to "How can I build a sand castle without shaping it like a castle?" You can't -- All you will have is a pile of sand.
The closest thing you could possible do is to allocate a block of memory the same size as your object:
byte[] fakeObject = new byte[sizeof(myStruct)];
(NOTE: even that will only work in MyStruct is a value type)

Related

How does Reflection retrieve data assigned to variables?

My understanding so far is that Reflection is used to retrieve the names of Types and their members from an assembly via its metadata. I've come across a few examples of Reflection in action identical to the following example.
class Person
{
public string Name {get;set;}
}
static void Main(string[] args)
{
Person person = new Person();
person.Name = "John";
Console.WriteLine(person.GetType().GetProperty("Name").GetValue(person)); //John
person.Name = "Mary";
Console.WriteLine(person.GetType().GetProperty("Name").GetValue(person)); //Mary
}
I understand how Reflection can get names of Types, members, etc. as this is what's stored in an assembly's metadata, but how does Reflection retrieve the value associated with it? This is dynamic data that changes during a program's execution (as shown in the example), which an assembly's metadata doesn't contain (right?).
Would be grateful for clarification on how Reflection retrieves actual values and whether this is actually the case. Please correct anything I've said that's not correct!
The short answer is that reflection is a feature of the runtime, so it has access to runtime information. Were it a separate library with no runtime "hooks", you're right, it wouldn't be able to get the values of properties at runtime, or make calls, or anything else that wouldn't be essentially observable from the assembly file on disk.
Long answer where I prove this to myself:
Microsoft makes available a reference version of the C# source code used to write the base class libraries for .NET Framework. If we look at the PropertyInfo.GetValue(object) method you use in your example, it's defined here. Following the trail of calls we eventually get to an abstract method of the same name but different parameters. Further down in the source file is the implementing class, RuntimePropertyInfo, and its override of GetValue we see that it is implemented by calling the property's get accessor (as, under the hood, properties are just collections of methods with certain signature conventions - GetGetMethod is a funny name meaning "get me the method defined as get for the current property"):
MethodInfo m = GetGetMethod(true);
if (m == null)
throw new ArgumentException(System.Environment.GetResourceString("Arg_GetMethNotFnd"));
return m.Invoke(obj, invokeAttr, binder, index, null);
If we do a similar spelunking journey on MethodInfo.Invoke, we eventually reach RuntimeMethodHandle.InvokeMethod, which is declared:
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static object InvokeMethod(object target, object[] arguments, Signature sig, bool constructor);
The extern keyword on a class means "I don't have the body for this method in C#, look elsewhere for it". For most users of C# this means they're using DllImport to reference native code, but this method has a different attribute: MethodImpl, with the MethodImplOptions.InternalCall enum value. This is the C# way of saying to the compiler, "I don't have the body, but the actual runtime itself does".
So at the end of our journey we reach the point where the Reflection API relies on the runtime itself. Of course, the runtime and the base class libraries have to be developed in tandem to ensure these sync-up points exist.
Interestingly, the actual standard for .NET - ECMA-335 - makes the Reflection API optional, when the implementation (meaning the runtime + base class libraries) adheres to the bare minimum "Kernel Profile" (cite: 6th Ed., §IV.4.1.3). So actually there are implementations of .NET where you're not explicitly allowed to inspect the runtime like this, but given the reliance some kinds of applications have on reflection, all big implementations (original .NET Framework, .NET Core / the new .NET, and Mono) provide it.
The TLDR is the CLR (Common Language Runtime) keeps track of all your objects in memory and when you call GetValue it retrieves the value for you.
Note this post is a little old, but here is a rough idea of what an object looks like in memory:
Please refer to the part that says Object Instance. An object laid out in memory, contains the following 4 items:
Syncblk
TypeHandle
Instance Fields
String Literals
When you call GetValue, using an OBJECTREF to the object instance, it finds the starting location where your instance fields are stored. From there it can figure out which instance to retrieve based on the type.
I believe the actual call is FieldDesc::GetInstanceField.

C# - Object Creation

I'm a PHP programmer for some time. Two days ago, I went to a job interview where they gave me an assigment to do in ASP.NET ( C# ). I would really like to get out of the php sphere of influence and learn a decent language that can challenge me. So, I have a question
Do all instances have to be instantiated at runtime? In php, I can do something like this...
class SomeObject {}
$objString = "SomeObject";
$objInstance = new $objString();
I can't do that in C#, probably beacuse it's a compiled language. In C#, would I have to create a Factory pattern who will instantiate objects. That would also mean that if I have to instantiate 10 object in that Factory, that there would be 10 if statements which is ugly.
I found Activator object with its Activator::createInstance() method but I could't get it to work. Also there's Reflection, but both of these ( as I'm aware of ) are a performance impact.
So, is there a way to dynamicly create objects or could it be that in C#, i can immediatlly create all objects that my program will use, which is really tempting?
EDIT
Ok, so let's say that I have 5 object that are used in 5 different occassions. I run the program, the program evaluates that it needs one of those object and instantiates it. The other four are never instantiated. I close the program.
Second time, I run the program with different parameters, and 2 of those 5 objects are created, other three never came into existence.
This is easy in PHP. Let's put Activator and other tools aside, is it good practice in C# world to create all the 5 objects when I know that maybe, only one of them will be used?
I don't know if i got your question wrong, but creating object of your given class SomeObject in C# is as easy as the following:
var obj = new SomeObject();
Using the Activator-Class it should look sth. like one of the following
var obj2 = Activator.CreateInstance(typeof(SomeObject));
var obj3 = Activator.CreateInstance<SomeObject>();`
var someObjType = Type.GetType("SomeObject"); // if you have to use a string
var obj4 = Activator.CreateInstance(someObjType);
Note that using the Activator-Class for instanciating objects isn't necessary in most cases. The first example is the standard way if you know the Type of the Class at compiletime.
UPDATE
regarding your update, since i don't know the details what comes to my mind is lazy instanciation. Since everything, including the entry point of your application is an object in C#, you can solve the issue using properies with backed fields like in the following example
class Program
{
// backing fields
private SomeObject obj1;
private SomeObject obj2;
private SomeObject obj3;
private SomeObject obj4;
private SomeObject obj5;
// this way, obj1 only gets instanciated when needed
public SomeObject Obj1
{
get
{
if (obj1 == null)
{
obj1 = new SomeObject();
}
return obj1;
}
}
// same for the other objects
[...]
}
I you are concerned about the memory usage of your object, i recommend you to learn about how to properly implement IDisposable
UPDATE 2
To provide the possibility recommended in the comments by # Mad Sorcerer, you could back the fields using the Lazy-Class which takes some effort of your shoulder, the effect is quite the same as in the previous update.
class Program
{
// Lazy backing fields
private Lazy<SomeObject> obj1 = new Lazy<SomeObject>();
private Lazy<SomeObject> obj2 = new Lazy<SomeObject>();
private Lazy<SomeObject> obj3 = new Lazy<SomeObject>();
private Lazy<SomeObject> obj4 = new Lazy<SomeObject>();
private Lazy<SomeObject> obj5 = new Lazy<SomeObject>();
// this way, obj1 only gets instanciated when needed
public SomeObject Obj1
{
get { return obj1.Value; }
}
// same for the other objects
[...]
}
Yes, you can create objects dynamically in C#. But not as easily as in PHP.
As you found, there's Activator. It works fine when you use it correctly. :) There's also direct reflection (Activator is based on reflection as well). Both are slow when used naively.
Using the Expression type, it is possible to cache the logic for instantiating an object. It's still slow the first time, but if you expect to be creating the same type of object repeatedly, this approach works well (and if you don't, then the fact that it's slow via Activator doesn't matter :) ).
That said, most of the time you should not need to create objects dynamically like in your example. The strong, compile-time type-checking in C# should be taken advantage of, not eschewed. Writing code that instantiates objects for which the type is already known at compile time is most efficient, and most type-safe.
For those relatively few times where you do need dynamic behavior, it is possible.
So that PHP code... you're choosing which class to instantiate by it's name as a string?
You need to look up the type first and then instantiate it with Activator.
Type classType = Type.GetType("SomeObject");
object instance = Activator.CreateInstance(classType);
You can look up it's constructor and call that instead using reflection which looks more like this
Type classType = Type.GetType("SomeObject");
var ctorInfo = classType.GetConstructor(Type.EmptyTypes);
object instance = ctorInfo.Invoke(new object[] {});
and you can cache the constructor as a delegate which eliminates the performance penalty which comes from looking up stuff#
Note that Type.GetType has some issues of it's own. The above code will work if SomeObject is in the System namespace. You may need to add the namespace, class and sometime assembly. In all it's safest to use the AssemblyQualifiedName.
There are a few ways to create an instance of a class in C#.
The usual way is simply to use new:
MyType myInstance = new MyType();
For dynamically creating objects, based on their name for instance, Activator.Createinstance() works, but you must know the assembly where that class is defined so you can correctly create that instance.
However, especially if you are just beginning, I wouldn't bother with getting into this yet.
C# is a statically-typed language, meaning that resolution of type is made during compilation.
On top of that, consider that the IDE, Visual Studio, will help you tremendously since it can scan files in your project and know the Type of each of members you are typing in your code.
Statically-types languages are helpful in avoiding the exact sort of issues that arise in purely dynamic languages: they force you to be coherent, at the expense of requiring you to be explicit in your declaration (although C#, with the var keyword, can help a lot in avoiding that normally required verbosity).
So the whole point is to make sure that you declare all types your will need in your application.
If you need a particular class member to accept data from multiple other classes, you can use inheritance, creating a base class that others will inherit some behaviour from, or use Interfaces, to describe common members to a variety of types. Each has its advantages and drawbacks.
If you are dabbling with C#, just experimenting, I'd recommend getting LINQpad. It may help you experiment while learning.
I would also stay away from anything that's not canonical: understand idiomatic C# first before you go too deep in trying to do do runtime stuff.
One area you can explore though, is the dynamic type. It's not as flexible as what you'd expect from a truly dynamic language, but it's a way to deal with type-uncertainty.
It has a performance drawback though, and should be avoided if you want to benefit from Intellisense in Visual Studio and want to benefit from the normal type-checking that the IDE and compiler can provide for you.

Are there any guidelines for declaring a method which accepts an anonymous object as its argument?

I want to write a method that accepts an anonymous object as its argument. When declaring such a method should the parameter be declared as object or dynamic?
public static void DoSomethingWith(dynamic details) { } OR
public static void DoSomethingWith(object details) { }
My application is a standalone application targetting .NET 4.0.
One reason why I seem to prefer 1 is because when you see the IntelliSense tip that shows the signature of the method, a dynamic argument more clearly states its intent than object.
I will stick with 1 unless there are better reasons to go with 2.
What have been your experiences with this?
If you are targetting framework 4.0 or higher, then its better to use dynamic.
public static void DoSomethingWith(dynamic details)
{
Console.Write(details.X);
Console.Write(details.Y);
}
And call it like:
DoSomethingWith(new { X = "ABC", Y = 10 });
This is hugely dependent on context. There are two existing answers shown that discuss the feature of dynamic that allows access to members, but there is a huge problem there in that it is not obvious to the caller that they are meant to provide those members. In those cases, a type that has those members would, in virtually all cases, be preferred.
In the main, usage of dynamic should be limited to those scenarios where you actually need it (talking to a dynamic type). If you are actually talking to a regular POCO object (maybe an anonymous type, etc), then object might avoid a few complications - but fundamentally object and dynamic are both implemented as object until you start accessing members.
Generally if you are passing a naked object to a method, you will be expecting the method to inspect it, perhaps via reflection. For those purposes, object will be absolutely fine, and provides direct access to .GetType().GetProperties() etc without any indirection.
Basically: without more context on what you are doing inside the method, it is impossible to conclude that either is "better" or "more appropriate", and inside the method dynamic and object are trivially interchangeable (a cast will always succeed, in either direction).
In this case, using dynamic has some advantages over object and no disadvantages that I can see, so your option 1 is clearly the way to go.
Option 1 allows you to use your parameter just as if you had declared it with the real type (which you can't do, since it is anonymous):
public static void DoSomethingWith(dynamic details)
{
var temp = details.Property; // Correct, as long as the object has a property called Property
}
With option 2, this code would have been illegal and you would have to resort to InvokeMethod() and the like, which is more cumbersome to use and to read without providing any real advantages.

Is new-ing objects obsolete?

Ok, so here's the question... is the new keyword obsolete?
Consider in C# (and java, I believe) there are strict rules for types. Classes are reference types and can only be created on the heap. POD types are created on the stack; if you want to allocate them on the heap you have to box them in an object type. In C#, structs are the exception, they can be created on the stack or heap.
Given these rules, does it make sense that we still have to use the new keyword? Wouldn't it make sense for the language to use the proper allocation strategy based on the type?
For example, we currently have to write:
SomeClassType x = new SomeClassType();
instead of
SomeClassType x = SomeClassType();
or even just
SomeClassType x;
The compiler would, based on that the type being created is a reference type, go ahead and allocate the memory for x on the heap.
This applies to other languages like ruby, php, et al. C/C++ allow the programmer more control over where objects are created, so it has good reason to require the new keyword.
Is new just a holdover from the 60's and our C based heritage?
SomeClassType x = SomeClassType();
in this case SomeClassType() might be a method located somewhere else, how would the compiler know whether to call this method or create a new class.
SomeClassType x;
This is not very useful, most people declare their variables like this and sometimes populate them later when they need to. So it wouldn't be useful to create an instance in memory each time you declare a variable.
Your third method will not work, since sometimes we want to define a object of one type and assign it to a variable of another type. For instance:
Stream strm = new NetworkStream();
I want a stream type (perhaps to pass on somewhere), but internally I want a NetworkStream type.
Also many times I create a new object while calling a method:
myobj.Foo(new NetworkStream());
doing that this way:
myobj.Foo(NetworkStream());
is very confusing. Am I creating an object, or calling a method when I say NetworkStream()?
If you could just write SomeClassType x; and have it automatically initialized, that wouldn't allow for constructors with any parameters. Not every SomeClassType will have a parameterless constructor; how would the compiler know what arguments to supply?
public class Repository
{
private IDbConnection connection;
public Repository(IDbConnection connection)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
this.connection = connection;
}
}
How would you instantiate this object with just Repository rep;? It requires a dependent object to function properly.
Not to mention, you might want to write code like so:
Dictionary<int, SomeClass> instances = GetInstancesFromSomewhere();
SomeClass instance;
if (instances.TryGetValue(1, out instance))
{
// Do something
}
Would you really want it auto-initializing for you?
If you just wrote SomeClassType x = SomeClassType() then this makes no distinction between a constructor and a method in scope.
More generally:
I think there's a fundamental misunderstanding of what the new keyword is for. The fact that value types are allocated on the stack and "reference" types are allocated on the heap is an implementation detail. The new keyword is part of the specification. As a programmer, you don't care whether or not it's allocated on the heap or stack (most of the time), but you do need to specify how the object gets initialized.
There are other valid types of initializers too, such as:
int[] values = { 1, 2, 3, 4 };
Voilà, an initialization with no new. In this case the compiler was smart enough to figure it out for you because you provided a literal expression that defines the entire object.
So I guess my "answer" is, don't worry about where the object exists memory-wise; use the new keyword as it's intended, as an object initializer for objects that require initialization.
For starters:
SomeClassType x;
is not initialized so no memory should be allocated.
Other than that, how do you avoid problems where there is a method with the same name as the class.
Say you write some code:
int World() { return 3; }
int hello = World();
and everything is nice and jolly.
Now you write a new Class later:
class World
{
...
}
Suddenly your int hello = World() line is ambiguous.
For performance reasons, this might be a bad idea. For instance, if you wanted to have x be a reference for an object that's already been created, it would be a waste of memory and processor time to create a new object then immediately dispose of it.
Wouldn't it make sense for the
language to use the proper allocation
strategy based on the type?
That's exactly what the C# compiler/runtime already does. The new keyword is just the syntax for constructing an object in whatever way makes sense for that object.
Removing the new keyword would make it less obvious that a constructor is being called. For a similar example, consider out parameters:
myDictionary.TryGetValue(key, out val);
The compiler already knows that val is an out. If you don't say so, it complains. But it makes the code more readable to have it stated.
At least, that is the justification - in modern IDEs these things could be found and highlighted in other ways besides actual inserted text.
Is new just a holdover from the 60's
and our C based heritage?
Definitely not. C doesn't have a new keyword.
I've been programming with Java for a number of years and I have never care if my object is on the heap or the stack. From that perspective is all the same to me to type new or don't type it.
I guess this would be more relevant for other languages.
The only thing I care is the class have the right operations and my objects are created properly.
BTW, I use ( or try ) to use the new keyword only in the factory merthod so my client looks like this anyway
SomeClasType x = SomeClasType.newInstance();
See: Effective Java Item:1
If you don't have a parameterless constructor, this could get ugly.
If you have multiple constructors, this could get real ugly.

What is the difference between Wrapper and Reflection

I was very confused about the reflection and wrapper, I know that reflection can reflect the object into another object type, wrapper can convert the primitive type into object. Is this correct?
A wrapper will wrap around another object which may hide some of the complexities of using the original object / provide diffrent naming conventions etc.
forgive the C# syntax and the fairly contrived example
class SimplePerson{
ComplexPerson _person;
public void WalkForward (int steps){
for (int i = 0; i < steps; i ++){
_person.LeftFoot ();
_person.MoveFoot ();
_person.PlaceFoot ();
}
}
// More methods
}
Reflection on the other hand can be used to retrieve methods / fields / properties and metadata in general from an object.
Again forgive the C#
SimplePerson _person;
Console.WriteLine ("Class {0} has the following methods:", _person.GetType().Name);
foreach (var method in _person.GetType().GetMethods()){
Console.WriteLine ("\t {0}", method.Name);
}
which should give output something like (depending on the class obviously)
Class SimplePerson has the following methods:
Eat
WalkForward
RunForward
Your concept of reflection is wrong. Reflection lets a program investigate its own classes at runtime. For example, you get an obect of an (at compile time) unknown class and find out which fields and methods it has.
A wrapper is simply a class that takes an object and wraps it, i.e. it adds (almost) no new functionality, but exposes a different interface than the original class. A special case are the wrappers for primitive types; since primitive types are not objects in some languages, e.g. Java, wrapper classes for those primitive classes allow for treating those primitve types like objects.
wrapper can convert the primitive type into object
Ehm, you seem to be confused. A "wrapper" is usually some code that hides an API ("wraps" it), to simplify calls etc. . You are probably thinking about autoboxing, which allows you to use primitive types like their corresponding objects and vice versa.
reflection can reflect the object into another object type
No, reflection allows you to retrieve information about available classes and their members at runtime, and to invoke their functionality, even if they're not available at compile time.
See http://java.sun.com/docs/books/tutorial/reflect/ for details. Please read this, then come back if you still are confused, and ask a new question.
I know that reflection can reflect the object into another object type
Not really. Reflection is used to dynamically access/modify objects at runtime.
Suppose you have the class Foo you can create an instance programatically with:
Object o = new Foo();
But you can also create an instance at runtime only with the name:
public Object createInstanceOf( String className )
throws InstantiationException,
IllegalAccessException {
return Class.forName( className ).newInstance();
}
Object o = createInstanceOf( "Foo" ) ;
That's basically what reflection is all about.
wrapper can convert the primitive type into object
In general terms a wrappers simply ... well wraps another object. In particular for Java primitives you're right, Java wrappers do wrap the primitives so they can be used as any other regular object, for instance to pass an int to an object that receive an object you'll have to use a wrapper:
public void somethingWith( Object o ) {}
....
int i = 1234;
somethingWith( new Integer( i ) );
Prior to java 1.5 you could not invoke the method somethingWith with out having to explicitly create the wrapper instance.
Today with autoboxing the compiler does that for you and you can invoke directly:
somethingWith( 1234 ) ;
I hope this helps and doesn't confuse you more.

Categories

Resources