Cast Between String and Classname

Cast between String and Classname

This solution is better than eval as you are evaluating params hash that might be manipulated by the user and could contain harmful actions. As a general rule: Never evaluate user input directly, that's a big security hole.

# Monkey patch for String class
class String
def to_class
klass = Kernel.const_get(self)
klass.is_a?(Class) ? klass : nil
rescue NameError
nil
end
end

# Examples
"Fixnum".to_class #=> Fixnum
"Something".to_class #=> nil

Update - a better version that works with namespaces:

 # Monkey patch for String class
class String
def to_class
chain = self.split "::"
klass = Kernel
chain.each do |klass_string|
klass = klass.const_get klass_string
end
klass.is_a?(Class) ? klass : nil
rescue NameError
nil
end
end

Cannot cast String to ClassName

Casting doesn't actually make a new object. You are trying to say to the compiler:

You think this is a reference to a type String; but trust me, I know it's a type Test.

It doesn't actually change the object in any way.

But if the reference is to an instance of String, it can't possibly also be a reference to an instance of Test, so the compiler forbids the cast: Test is not a subclass of String.

To convert a String to a Test, you actually need to construct an instance of Test. For instance, there may be a constructor which takes a String; then:

Test test1 = new Test1(s);

or maybe there's a static factory method:

Test test1 = Test1.buildFromString(s);

How to convert a string with the name of a class to the class type itself?

You can get your class back from string, but you need to use your project's module name while getting class name. If you don't use your module name then it will return nil because the class name you have referenced earlier is not fully qualified by the module name. You should change the class name string to represent the fully qualified name of your class:

let myClassString = String(MyModule.MyViewController.self)
print(myClassString)
let myClass = NSClassFromString("MyModule.\(myClassString)") as! MyViewController.Type
print(myClass)

JAVA - cast using class obtained by its name (string value)

What you are trying to do is unnecessary because your list is declared as List<Object> so the cast is not needed.

-- Before Edit --

Not sure I understand what you need, but did you try to use:

Class.cast(object)

This is a method of the java.lang.Class

Dynamically Converting strings into Class Name in same namespace Type.GetType() returning null

Please Provide full path of your object means with namespace
Like

      String p = "ConsoleApplication1.Profile_UC";
Type uc1 = Type.GetType(p);

How to convert String type to Class type in java

Class<?> classType = Class.forName(className);

Make sure className is fully qualified class name like com.package.class Also, please share your error message that you see.

It is possible to convert from a string to class name in PHP

Consider this Simple Scenario:

<?php
class SomeClass{
public static $a = 12;
public static $b = "some value";
public static $c = "another value";

public static function getSomeData(){
return self::$a . " " . self::$b . " " . self::$c;
}
}

$b = SomeClass::getSomeData();
//DUMPS '12 some value another value' TO THE OUTPUT STREAM...
var_dump($b);

$strClassName = "SomeClass";

//STILL DUMPS '12 some value another value' TO THE OUTPUT STREAM...
var_dump(call_user_func($strClassName. "::getSomeData"));

Extending this Knowledge to your Unique Case, You might want to do something like:

        <?php
$table = Teller::select('*')->where('user_id','=', $this->user_id)->first();
$modelName = trim($table->tables,'"');
$implicitCall = call_user_func($modelName. "::select", '*');
$implicitCall = call_user_func($modelName. "::where", array('id', '=', $id));
$loan = call_user_func($modelName. "::get");

?>

Optionally; You may even take this a little further. Since we know that you are using Fluent Setters; it is clear that the First implicit call will return an instance of the Class so we could do something like so:

    <?php
$table = Teller::select('*')->where('user_id','=', $this->user_id)->first();
$modelName = trim($table->tables,'"');

// THIS SHOULD RETURN AN INSTANCE OF THE CLASS IN QUESTION: THE MODEL CLASS
$implicitCall = call_user_func($modelName. "::select", '*');

// DO YOU DOUBT IT? WELL, DOUBT IS THE BEGINNING OF ALL KNOWLEDGE.
// I DOUBT IT TOO; SO LET'S CONFIRM OUR DOUBTS
var_dump($implicitCall); // EXPECTED TO DUMP THE CLASS IN QUESTION.

// NOW WE CAN JUST USE THE $implicitCall VARIABLE AS IF IT WAS AN INSTANCE OF THE MODEL CLASS LIKE SO:
$loan = $implicitCall->where('id','=', $id)->get();

?>

I hope this answers helps and works for you though... ;-)

Converting a string to a class name

Well, for one thing ArrayList isn't generic... did you mean List<Customer>?

You can use Type.GetType(string) to get the Type object associated with a type by its name. If the assembly isn't either mscorlib or the currently executing type, you'll need to include the assembly name. Either way you'll need the namespace too.

Are you sure you really need a generic type? Generics mostly provide compile-time type safety, which clearly you won't have much of if you're finding the type at execution time. You may find it useful though...

Type elementType = Type.GetType("FullyQualifiedName.Of.Customer");
Type listType = typeof(List<>).MakeGenericType(new Type[] { elementType });

object list = Activator.CreateInstance(listType);

If you need to do anything with that list, you may well need to do more generic reflection though... e.g. to call a generic method.

Convert String value to a Java Class name

Try ::

Intent resumeIntent = new Intent (this, Class.forName(getPackageName() + resumeName);
startActivity(resumeIntent);

UPDATE

String resumeName = YourActivityName.class.getCanonicalName();
try {
Class newClass = Class.forName(resumeName);
Intent resume = new Intent(this, newClass);
startActivity(resume);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

Store the canonical name of the activity in the string variable.



Related Topics



Leave a reply



Submit