why do i get this exception?
Map myHash = null
myHash = (HashMap)Collections.synchronizedMap(new HashMap());
If i try to use this hashmap, i get java.lang.ClassCastException
I was reading a question on making a generic property, but I'm a little confused at by the last example from the first answer (I've included the relevant code below):
You have to know the type at compile
time. If you don't know the type at
compile time then you must be storing
it in an object, in which case you can
add the following property to the Foo
class:
public object ConvertedValue {
get {
return Convert.ChangeType(Value, Type);
}
}
That's seems strange: it's converting the value to the specified type, but it's returning it as an object when the value was stored as an object. Doesn't the returned object still require un-boxing? If it does, then why bother with the conversion of the type?
I'm also trying to make a generic property whose type will be determined at run time:
public class Foo
{
object Value {get;set;}
Type ValType{get;set;}
Foo(object value, Type type)
{ Value = value; ValType = type; }
// I need a property that is actually
// returned as the specified value type...
public object ConvertedValue {
get {
return Convert.ChangeType(Value, ValType);
}
}
}
Is it possible to make a generic property? Does the return property still require unboxing after it's accessed?
In postgres I have a table with a varchar column. The data is supposed to be integers and I need it in iteger type in a query. Some values are empty strings.
The following:
SELECT myfield::integer FROM mytable
yields ERROR: invalid input syntax for integer: ""
How can I query a cast and have 0 in case of error during the cast in postgres?
I'm having some trouble to do the following:
int[] tmpIntList = (int[])MyArrayList.toArray(someValue);
MyArrayList contains only numbers. I get a typecast error since ArrayList only returns Object[] but why isnt it possible to turn it into a int[] ?
hi there
i design a multilayer we appliction andusing LINQ a my data provider
i need to user my own Entites instead o LINQ etities. so i created Entities Project and create my entities in it.
when i get data from contex and cast them to my entities , everything is ok.
but when i want to cast on of my entities to linq entity , an exception thrown.
in my linq entity i add CTYPE operator from and to my entities
Exp :
Public Class BaseController(Of LinqEntity As {BaseEntity, New}, MyEntity As ModuleEntities.BaseEntityInfo)
Implements Interfaces.Base(Of ServiceEntity)
'This methd work fine and cast LinqEntity to MyEntity
Public Function GetAll() As List(Of MyEntity )
Dim q = (From x In Context.GetTable(Of LinqEntity)() _
Select x).Cast(Of MyEntityBase)
End Function
Public Sub Update(ByVal entity As MyEntity)
'here is problem
'cast , direct cast , or anything not work
Dim x as LinqEntity = entity
Me.Context.GetTable(Of LinqEntity).InsertOnSubmit(entity)
Me.Context.SubmiChanges()
End Sub
i am trying to call a function that is defined in a class RFIDeas_Wrapper(dll being used).
But when i checked for type of reader and after that i used it to call function it shows me error Cannot convert type T to RFIDeas_Wrapper.
EDIT
private List<string> GetTagCollection<T>(T Reader)
{
TagCollection = new List<string>();
if (Reader.GetType() == typeof(RFIDeas_Wrapper))
{
((RFIDeas_Wrapper)Reader).OpenDevice();
// here Reader is of type RFIDeas_Wrapper
//, but i m not able to convert Reader into its datatype.
string Tag_Id = ((RFIDeas_Wrapper)Reader).TagID();
//Adds Valid Tag Ids into the collection
if(Tag_Id!="0")
TagCollection.Add(Tag_Id);
}
else if (Reader.GetType() == typeof(AlienReader))
TagCollection = ((AlienReader)Reader).TagCollection;
return TagCollection;
}
((RFIDeas_Wrapper)Reader).OpenDevice(); , ((AlienReader)Reader).TagCollection;
I want this line to be executed without any issue. As Reader will always be of the type i m specifying.
How to make compiler understand the same thing.
Hello there, I would appreciate it if anyone can answer my question.
Identify the implicit cast and explicit cast?
int a = 2, b = 3;
float f = 2.5;
double d = -1.2;
int int_result;
float real_result;
Is it possible (or even advisable) to cast the element retrieved from a for each statement in the statement itself? I do know that each element in list will be of type .
I.E.:
List<BaseType> list = DAO.getList();
for(<SubType> element : list){
// Cannot convert from element type <BaseType> to <SubType>
...
}
rather than:
List <BaseType> list = DAO.getList();
for(<BaseType> el : list){
<SubType> element = (<SubType>)el;
...
}
I have a simple application to store address details and edit them. I have been away from VB for a few years now and need to refreash my knowledge while working to a tight deadline. I have a general Sub responsible for displaying a form where user can add contact details (by pressing button add) and edit them (by pressing button edit). This sub is stored in a class Contact. The way it is supposed to work is that there is a list with all the contacts and when new contact is added a new entry is displayed. If user wants to edit given entry he or she selects it and presses edit button
Public Sub Display()
Dim C As New Contact
C.Cont = InputBox("Enter a title for this contact.")
C.Fname = frmAddCont.txtFName.Text
C.Surname = frmAddCont.txtSName.Text
C.Address = frmAddCont.txtAddress.Text
frmStart.lstContact.Items.Add(C.Cont.ToString)
End Sub
I call it from the form responsible for adding new contacts by
Dim C As New Contact
C.Display()
and it works just fine. However when I try to do something similar using the edit button I get errors - "Unable to cast object of type 'System.String' to type 'AddressBook.Contact'."
Dim C As Contact
If lstContact.SelectedItem IsNot Nothing Then
C = lstContact.SelectedItem()
C.Display()
End If
I think it may be something simple however I wasn't able to fix it and given short time I have I decided to ask for help here.
I have updated my class with advice from other members and here is the final version (there are some problems however). When I click on the edit button it displays only the input box for the title of the contact and actually adds another entry in the list with previous data for first name, second name etc.
Public Class Contact
Public Contact As String
Public Fname As String
Public Surname As String
Public Address As String
Private myCont As String
Public Property Cont()
Get
Return myCont
End Get
Set(ByVal value)
myCont = Value
End Set
End Property
Public Overrides Function ToString() As String
Return Me.Cont
End Function
Sub NewContact()
FName = frmAddCont.txtFName.ToString
frmStart.lstContact.Items.Add(FName)
frmAddCont.Hide()
End Sub
Public Sub Display()
Dim C As New Contact
C.Cont = InputBox("Enter a title for this contact.")
C.Fname = frmAddCont.txtFName.Text
C.Surname = frmAddCont.txtSName.Text
C.Address = frmAddCont.txtAddress.Text
'frmStart.lstContact.Items.Add(C.Cont.ToString)
frmStart.lstContact.Items.Add(C)
End Sub
End Class
I was wondering if there is a way in C++ to accomplish the following:
I have a base class called ResultBase and two class that are Derived from it, Variable and Expression. I have a few methods that do work on vector<ResultBase> . I want to be able to pass in vectors of Variable and Expression into these methods. I can achieve this by creating a vector<ResultBase> and using static_cast to fill it with the members from my vector of Variable/Expression. However, once the vector has run through the methods, I want to be able to get it back as the vector of Result/Expression. I'll know for sure which one I want back. static_cast won't work here as there isn't a method to reconstruct a Variable/Expression from a ResultBase, and more importantly I wouldn't have the original properties of the Variables/Expressions
The methods modify some of the properties of the ResultBase and I need those changes to be reflected in the original vectors. (i.e. ResultBase has a property called IsLive, and one of the methods will modify this property. I want this IsLive value to be reflected in the derived class used to create the ResultBase
Whats the easiest way to accomplish this?
Well I'm tring to get class members values from a dynamically casted class but I'm unable to find its child class members values.
Right now I'm getting TotalWeight members property, but I also want to get child member property of AnotherClass like AnotherClass.child. How can I get those members?
string ClassName="something";
Type types = Type.GetType(ClassName, false);
var d = from source in types.GetMembers().ToList()
where source.MemberType == MemberTypes.Property
select source;
List<MemberInfo> members = d.Where(memberInfo =>
d.Select(c => c.Name)
.ToList()
.Contains(memberInfo.Name))
.ToList();
PropertyInfo propertyInfo;
object value;
foreach (var memberInfo in members)
{
propertyInfo = typeof(T).GetProperty(memberInfo.Name);
if (myobj.GetType().GetProperty(memberInfo.Name) != null)
{
value = myobj.GetType()
.GetProperty(memberInfo.Name)
.GetValue(myobj, null);
//how to get child members value here?
}
}
//Where class something has member
public class something
{
private decimal _totalWeight;
private Anotherclass _another;
public decimal TotalWeight
{
get
{
return this._totalWeight;
}
set
{
this._totalWeight = value;
}
}
public Anotherclass Another
{
get
{
return this._another;
}
set
{
this._another= value;
}
}
}
I have two functions that do the exact same thing but in two different types of struct and this two types of struct are very similar.
Imagine I have this two structs.
typedef struct nodeOne{
Date *date;
struct nodeOne *next;
struct nodeOne *prev;
}NodeOne;
typedef struct nodeTwo{
Date *date;
struct nodeTwo *next;
struct nodeTwo *prev;
}NodeTwo;
Since my function to destroy each of the list is almost the same (Just the type of the arguments are different) I would like to make just one function to make the two thins.
I have this two functions
void destroyListOne(NodeOne **head, NodeOne **tail){
NodeOne *aux;
while (*head != NULL){
aux = *head;
*head = (*head)->next;
free(aux);
}
*tail = NULL;
}
and this one:
void destroyListTwo(NodeTwo **head, NodeTwo **tail){
NodeTwo *aux;
while (*head != NULL){
aux = *head;
*head = (*head)->next;
free(aux);
}
*tail = NULL;
}
Since they are very similar I thought making something like this:
void destroyList(void **ini, void **end, int listType){
if (listType == 0) {
NodeOne *aux;
NodeOne head = (NodeOne) ini;
NodeOne tail = (NodeOne) ed;
}
else {
NodeTwo *aux;
NodeTwo head = (NodeTwo) ini;
NodeTwo tail = (NodeTwo) ed;
}
while (*head != NULL){
aux = *head;
*head = (*head)->next;
free(aux);
}
*tail = NULL;
}
As you may now this is not working but I want to know if this is possible to achieve.
I must maintain both of the structs as they are.
I am extending the ImageBox control from EmguCV. The control's Image property can be set to anything implementing the IImage interface.
All of the following implement this interface:
Image<Bgr, Byte>
Image<Ycc, Byte>
Image<Hsv, Byte>
Now I want to call the Draw method on the object of the above type (what ever it may be).
The problem is when I access the Image property, the return type is IImage. IImage does not implement the Draw method, but all of the above do.
I believe I can cast the object of type IImage to one of the above (the right one) and I can access the Draw method. But how do I know what the right one is? If you have a better way of doing this, please suggest that as well.
Can you cast an object to one that implements an interface? Right now, I'm building a GUI, and I don't want to rewrite the Confirm/Cancel code (A confirmation pop-up) over and over again.
So, what I'm trying to do is write a class that gets passed the class it's used in and tells the class whether or not the user pressed Confirm or Cancel. The class always implements a certain interface.
Code:
class ConfirmFrame extends JFrame implements ActionListener
{
JButton confirm = new JButton("Confirm");
JButton cancel = new JButton("Cancel");
Object o;
public ConfirmFrame(Object o)
{
// Irrelevant code here
add(confirm);
add(cancel);
this.o = (/*What goes here?*/)o;
}
public void actionPerformed( ActionEvent evt)
{
o.actionPerformed(evt);
}
}
I realize that I'm probably over-complicating things, but now that I've run across this, I really want to know if you can cast an object to another object that implements a certain interface.
The answers to the following question describe the recommended usage of static_cast, dynamic_cast, and reinterpret_cast in C++:
http://stackoverflow.com/questions/332030/when-should-static-cast-dynamic-cast-and-reinterpret-cast-be-used
Do you know of any tools that can be used to detect misuse of these kinds of cast? Would a static analysis tool like PC-Lint or Coverity Static Analysis do this?
The particular case that prompted this question was the inappropriate use of static_cast to downcast a pointer, which the compiler does not warn about. I'd like to detect this case using a tool, and not assume that developers will never make this mistake.
Hi,
Can someone complete the code on an easy way?
float[] floats = {...}; // create an array
// Now I want to create a new array of ints from the arrays floats
int[] ints = ????;
I know I can simply cast element by element to a new array. But is it possible on an easier way?
Thanks
I want these two print functions to do the same thing:
unsigned int Arraye[] = {0xffff,0xefef,65,66,67,68,69,0};
char Arrage[] = {0xffff,0xefef,65,66,67,68,69,0};
printf("%s", (char*)(2+ Arraye));
printf("%s", (char*)(2+ Arrage));
where Array is an unsigned int. Normally, I would change the type but, the problem is that most of the array is numbers, although the particular section should be printed as ASCII.
You would think there would be a way using DirectCast, TryCast, CType etc but all of them seem to choke on it e.g.:
CType("Yes", Boolean)
You get:
System.InvalidCastException -
Conversion from string "Yes" to type
'Boolean' is not valid.
Hello !
When I try to cast
$value = floatval('14,5833');
to a float type I expect a value with dot like 14.5833 but it returns me 14,5833.
How should I do this ?
I wouldn't like to use any string replace functions.
I'm a bit new to PHP, and I'm more experienced with strongly-typed languages such as JAVA, C# or C++.I'm currently writing a web tool in PHP, and I am having an issue trying to do what I want.
The simple idea of what I want to do in code is run through some emails I used PHP-IMAP to get. I then create email objects (a class I defined), and put them in an array.
Later on the code, however, I cycle through those emails to display them.
However, as you might have guessed I'd have an issue with, I try to use an Email Class object method in that later loop -- and I'm pretty sure PHP doesn't know that the variables in the array happen to be Email Class objects!
I wrote a toString method, and I want to call it in the loop.
While I don't need to do this for the final version of this tool, I would like to find out what I'm missing.
This is the class and the loop where I'm calling the method:
include 'imap_email_interface.php';
class ImapEmail implements imap_email_interface
{
// Email data
var $msgno;
var $to;
var $from;
var $subject;
var $body;
var $attachment;
// Email behavior
/* PHP 4 ~ legacy constructor */
public function ImapEmail($message_number)
{
$this->__construct();
$this->msgno = $message_number;
}
/* PHP 5 Constructor */
public function __construct($message_number)
{ $this->msgno = $message_number; }
public function send($send_to)
{
// Not Yet Needed! Seriously!
}
public function setHeaderDirectly($TO, $FROM, $SUBJECT)
{ $this->to = $TO; $this->from = $FROM; $this->subject = $SUBJECT; }
public function setHeaderIndirectly($HEADER)
{
if (isset($HEADER->to[0]->personal))
$this->to = '"'.$HEADER->to[0]->personal.'", '.$HEADER->to[0]->mailbox.'@'.$HEADER->to[0]->host;
else
$this->to = $HEADER->to[0]->mailbox.'@'.$HEADER->to[0]->host;
$this->from = '"'.$HEADER->from[0]->personal.'", '.$HEADER->from[0]->mailbox.'@'.$HEADER->from[0]->host;
$this->subject = $HEADER->subject;
}
public function setBody($BODY)
{ $this->body = $BODY; }
public function setAttachment($ATTCH)
{
$this->attachment = $ATTCH;
}
public function toString()
{
$str = '[TO]: ' . $this->to . '<br />' . '[FROM]: ' . $this->from . '<br />' . '[SUBJECT]: ' . $this->subject . '<br />';
$str .= '[Attachment]: '.$this->attachment.'<br />';
return $str;
}
}
?>
The Loop:
foreach ($orderFileEmails as $x)
{
$x->toString();
echo '<br /><br />';
}
Any ideas?
I have an interface between a client and a server where a client sends (1) an unsigned value, and (2) a flag which indicates if value is signed/unsigned. Server would then static cast unsigned value to appropriate type.
I later found out that this is implementation defined behavior and I've been reading about it but I couldn't seem to find an appropriate solution that's completely safe? I've read about type punning, pointer conversions, and memcpy.
Would simply using a union type work? A UnionType containing signed and unsigned int, along with the signed/unsigned flag. For signed values, client sets the signed part of the union, and server reads the signed part. Same for the unsigned part. Or am I completely misunderstanding something?
Side question: how do I know the specific behavior in this case for a specific scenario, e.g. windriver diab on PPC? I'm a bit lost on how to find such documentation.
So I've written a quick bit of code to help quickly convert between business objects and view models. Not to pimp my own blog, but you can find the details here if you're interested or need to know.
One issue I've run in to is that I have a custom collection type, ProductCollection, and I need to turn that in to a string[] in on my model. Obviously, since there is no default implicit cast, I'm getting an exception in my contract converter.
So, I thought I would write the next little bit of code and that should solve the problem:
public static implicit operator string[](ProductCollection collection) {
var list = new List<string>();
foreach (var product in collection)
{
if (product.Id == null)
{
list.Add(null);
}
else
{
list.Add(product.Id.ToString());
}
}
return list.ToArray();
}
However, it still fails with the same cast exception. I'm wondering if it has something to do with being in reflection? If so, is there anything that I can do here?? I'm open to architectural solutions, too!
Hi all,
I made a private API that assumes that the address of the first member-object in the class will be the same as the class's this-pointer... that way the member-object can trivially derive a pointer to the object that it is a member of, without having to store a pointer explicitly.
Given that I am willing to make sure that the container class won't inherit from any superclass, won't have any virtual methods, and that the member-object that does this trick will be the first member object declared, will that assumption hold valid for any C++ compiler, or do I need to use the offsetof() operator (or similar) to guarantee correctness?
To put it another way, the code below does what I expect under g++, but will it work everywhere?
class MyContainer
{
public:
MyContainer() {}
~MyContainer() {} // non-virtual dtor
private:
class MyContained
{
public:
MyContained() {}
~MyContained() {}
// Given that the only place Contained objects are declared is m_contained
// (below), will this work as expected on any C++ compiler?
MyContainer * GetPointerToMyContainer()
{
return reinterpret_cast<MyContainer *>(this);
}
};
MyContained m_contained; // MUST BE FIRST MEMBER ITEM DECLARED IN MyContainer
int m_foo; // other member items may be declared after m_contained
float m_bar;
};
I'm getting a very weird error.
I have 2 activities. On both I'm getting the SharedPreferences using MODE_PRIVATE (if it matters) by sp = getPreferences(MODE_PRIVATE); on each activity's onCreate()
I'm calling sp.getBoolean(IntroActivity.SHOW_INTRO, true)
On the IntroActivity this works fine. But when I'm trying in the main activity, I'm getting this
10-12 04:55:23.208: E/AndroidRuntime(11668): FATAL EXCEPTION: main
10-12 04:55:23.208: E/AndroidRuntime(11668): java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean
10-12 04:55:23.208: E/AndroidRuntime(11668): at android.app.SharedPreferencesImpl.getBoolean(SharedPreferencesImpl.java:242)
10-12 04:55:23.208: E/AndroidRuntime(11668): at com.lablabla.parkme.ParkMeActivity$2.onClick(ParkMeActivity.java:194)
10-12 04:55:23.208: E/AndroidRuntime(11668): at android.view.View.performClick(View.java:4084)
10-12 04:55:23.208: E/AndroidRuntime(11668): at android.view.View$PerformClick.run(View.java:16966)
10-12 04:55:23.208: E/AndroidRuntime(11668): at android.os.Handler.handleCallback(Handler.java:615)
10-12 04:55:23.208: E/AndroidRuntime(11668): at android.os.Handler.dispatchMessage(Handler.java:92)
10-12 04:55:23.208: E/AndroidRuntime(11668): at android.os.Looper.loop(Looper.java:137)
10-12 04:55:23.208: E/AndroidRuntime(11668): at android.app.ActivityThread.main(ActivityThread.java:4745)
10-12 04:55:23.208: E/AndroidRuntime(11668): at java.lang.reflect.Method.invokeNative(Native Method)
10-12 04:55:23.208: E/AndroidRuntime(11668): at java.lang.reflect.Method.invoke(Method.java:511)
10-12 04:55:23.208: E/AndroidRuntime(11668): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-12 04:55:23.208: E/AndroidRuntime(11668): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-12 04:55:23.208: E/AndroidRuntime(11668): at dalvik.system.NativeStart.main(Native Method)
I made sure that I'm not putting a String somewhere in the middle with that same key
Any ideas?
Thanks!
EDIT:
some code:
//onCreate()
sp = getPreferences(MODE_PRIVATE);
// other method
boolean showIntro = sp.getBoolean(IntroActivity.SHOW_INTRO, true); // Exception is here
showIntroCheckBox.setChecked(showIntro);
If it matters, the code which throws the exception is inside a button's onClick
I have .NET project with sync framework and two separate Datasets for MS SQL and Compact SQL. in my base class I have a generic DataTable object. in my derived classed I assign Typed DataTable to the generic object based on whether the application is operating online or offline: example:
if (online)
_dataTable = new MSSQLDataSet.Customer;
else
_dataTable = new CompactSQLDataSet.Customer;
Now every where in my code i have to check and do a cast based on the current network mode like this:
public void changeCustomerID(int ID)
{
if (online)
(MSSQLDataSet.CustomerDataTable)_dataTable)[i].CustomerID = value;
else
(CompactMSSQLDataSet.CustomerDataTable)_dataTable)[i].CustomerID = value;
}
but I don't think this is very efficient and I believe it can be done in a smarter way to only use one line of code by dynamically getting the Type of _dataTable on the run time.
my problem is at the design time, in order to acess datatable porperties such as "CustomerID" it has to be casted to either MSSQLDataSet.CustomerDataTable or CompactMSSQLDataSet.CustomerDataTable.
Is there a way to have a function or a operator to convert the _datatable to its runtime type but still be able to use it's design time properties which are the same between the two types? something like:
((aType)_dataTable)[i].CustomerID = value;
//or
GetRuntimeType(_dataTable)[i].CustomerID = value;